Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.50/6: Рейтинг темы: голосов - 6, средняя оценка - 4.50
 Аватар для eXPonent
99 / 52 / 27
Регистрация: 21.05.2012
Сообщений: 1,170

Добавить функцию в класс ifstream

27.02.2017, 15:47. Показов 1425. Ответов 15

Студворк — интернет-сервис помощи студентам
имеется функция:
C++
1
2
3
4
5
bool Str(ifstream &f, const char *s)
{
    char buff[12];
    return !(f.get(buff, 12)&&strcmp(buff,s)&&f.ignore(std::numeric_limits<std::streamsize>::max(),'\n'));
}
как её переписать так что бы добавить в класс ifstream
что бы вызывалась так:
C++
1
f.Str("text");
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
27.02.2017, 15:47
Ответы с готовыми решениями:

Создайте класс Date. Добавить в строковый класс функцию
3)Создайте класс Date, который будет содержать информацию о дате (день, месяц, год). С помощью механизма перегрузки операторов, определите...

Добавить в строковый класс функцию
Добавить в строковый класс функцию, которая создает строку, содержащую пересечение двух строк, то есть общие символы для двух строк. ...

Как добавить функцию в класс
Например у меня есть функция void Circle(HDC h, int R, int X, int Y) И мне ее нужно добавить в класс. Но эти параметры (HDC h,...

15
Модератор
Эксперт С++
 Аватар для zss
13773 / 10966 / 6491
Регистрация: 18.12.2011
Сообщений: 29,244
27.02.2017, 15:57
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <fstream>
#include <limits>
using namespace std;
class MyIfstream:public ifstream
{
public:
    bool Str(const char *s)
    {
        char buff[12];
        return 
            !( this->get(buff, 12) && 
               strcmp(buff,s) &&
               this->ignore(std::numeric_limits<std::streamsize>::max(),'\n')
               );
    }
};
int main() 
{
    MyIfstream f;
    bool res=f.Str("text");
    cout<<res<<endl;
    system("pause");
    return 0;
}
1
 Аватар для eXPonent
99 / 52 / 27
Регистрация: 21.05.2012
Сообщений: 1,170
27.02.2017, 18:05  [ТС]
А можно как то
Цитата Сообщение от zss Посмотреть сообщение
C++
1
2
char buff[12]; 
return
объединить?
что бы прога работала быстрее
потому что препод сказал, что функция состоящая из одного return
не резервируется как функция, а вставляется в сам код
и работает быстрее
0
Модератор
Эксперт С++
 Аватар для zss
13773 / 10966 / 6491
Регистрация: 18.12.2011
Сообщений: 29,244
27.02.2017, 19:05
Тогда надо убрать описание функции из объявления класса.
Функция перестанет считаться inline функцией
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <fstream>
#include <limits>
using namespace std;
class MyIfstream:public ifstream
{
public:
    bool Str(const char *s);
};
bool MyIfstream::Str(const char *s)
{
        char buff[12];
        return 
            !( this->get(buff, 12) && 
               strcmp(buff,s) &&
               this->ignore(std::numeric_limits<std::streamsize>::max(),'\n')
               );
}
int main() 
{
    MyIfstream f;
    bool res=f.Str("text");
    cout<<res<<endl;
    system("pause");
    return 0;
}
Кстати, более понятной она станет, если ее написать так
C++
1
2
3
4
5
6
7
8
bool MyIfstream::Str(const char *s)
{
        char buff[12];
        bool t = this->get(buff, 12);
        t &&= strcmp(buff,s);
        t &&= this->ignore(std::numeric_limits<std::streamsize>::max(),'\n');
        return !t;
 }
1
 Аватар для eXPonent
99 / 52 / 27
Регистрация: 21.05.2012
Сообщений: 1,170
27.02.2017, 19:40  [ТС]
Цитата Сообщение от zss Посмотреть сообщение
Тогда надо убрать описание функции из объявления класса.
Функция перестанет считаться inline функцией
А можете показать код, если не сложно?
0
nd2
3438 / 2817 / 1249
Регистрация: 29.01.2016
Сообщений: 9,427
27.02.2017, 19:45
Цитата Сообщение от eXPonent Посмотреть сообщение
А можете показать код, если не сложно?
Тебе же нужно, чтобы код быстрее работал? inline быстрее работает.
0
Модератор
Эксперт С++
 Аватар для zss
13773 / 10966 / 6491
Регистрация: 18.12.2011
Сообщений: 29,244
27.02.2017, 21:55
Цитата Сообщение от eXPonent Посмотреть сообщение
А можете показать код
уже показал (пост 4)
0
 Аватар для eXPonent
99 / 52 / 27
Регистрация: 21.05.2012
Сообщений: 1,170
28.02.2017, 01:27  [ТС]
На строчке кода
C++
1
MyIfstream feng(Name[N]), frus("_"+Name[N]);
ошибка:
Кликните здесь для просмотра всего текста
Ошибка 1 error C2664: MyIfstream::MyIfstream(const MyIfstream &): невозможно преобразовать параметр 1 из "const std::string" в "const MyIfstream &" c:\users\1\desktop\colonization\coloniza tion\colonization.cpp 124 1 Colonization

Ошибка 2 error C2664: MyIfstream::MyIfstream(const MyIfstream &): невозможно преобразовать параметр 1 из "std::basic_string<_Elem,_Traits,_Ax >" в "const MyIfstream &" c:\users\1\desktop\colonization\coloniza tion\colonization.cpp 124 1 Colonization
0
Любитель чаепитий
 Аватар для GbaLog-
3745 / 1801 / 566
Регистрация: 24.08.2014
Сообщений: 6,020
Записей в блоге: 1
28.02.2017, 06:16
Надо добавить
C++
1
using ifstream::ifstream;
В теле класса.
0
 Аватар для eXPonent
99 / 52 / 27
Регистрация: 21.05.2012
Сообщений: 1,170
28.02.2017, 16:08  [ТС]
А что эта строчка означает?
мы используем пространство ifstream для ifstream ?
0
Любитель чаепитий
 Аватар для GbaLog-
3745 / 1801 / 566
Регистрация: 24.08.2014
Сообщений: 6,020
Записей в блоге: 1
28.02.2017, 16:22
Цитата Сообщение от eXPonent Посмотреть сообщение
А что эта строчка означает?
Так называемое наследование конструкторов:
http://en.cppreference.com/w/c... eclaration
Inheriting constructors
If the using-declaration refers to a constructor of a direct base of the class being defined (e.g. using Base::Base;), constructors of that base class are inherited, according to the following rules:
1) A set of candidate inheriting constructors is composed of
a) All non-template constructors of the base class (after omitting ellipsis parameters, if any) (since C++14)
b) For each constructor with default arguments or the ellipsis parameter, all constructor signatures that are formed by dropping the ellipsis and omitting default arguments from the ends of argument lists one by one
c) All constructor templates of the base class (after omitting ellipsis parameters, if any) (since C++14)
d) For each constructor template with default arguments or the ellipsis, all constructor signatures that are formed by dropping the ellipsis and omitting default arguments from the ends of argument lists one by one
2) All candidate inherited constructors that aren't the default constructor or the copy/move constructor and whose signatures do not match user-defined constructors in the derived class, are implicitly declared in the derived class. The default parameters are not inherited:
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
struct B1 {
    B1(int);
};
struct D1 : B1 {
    using B1::B1;
// The set of candidate inherited constructors is 
// 1. B1(const B1&)
// 2. B1(B1&&)
// 3. B1(int)
 
// D1 has the following constructors:
// 1. D1()
// 2. D1(const D1&) 
// 3. D1(D1&&)
// 4. D1(int) <- inherited
};
 
struct B2 {
    B2(int = 13, int = 42);
};
struct D2 : B2 {
    using B2::B2;
// The set of candidate inherited constructors is
// 1. B2(const B2&)
// 2. B2(B2&&)
// 3. B2(int = 13, int = 42)
// 4. B2(int = 13)
// 5. B2()
 
// D2 has the following constructors:
// 1. D2()
// 2. D2(const D2&)
// 3. D2(D2&&)
// 4. D2(int, int) <- inherited
// 5. D2(int) <- inherited
};
The inherited constructors are equivalent to user-defined constructors with an empty body and with a member initializer list consisting of a single nested-name-specifier, which forwards all of its arguments to the base class constructor.
It has the same access as the corresponding base constructor. It is constexpr if the user-defined constructor would have satisfied constexpr constructor requirements. It is deleted if the corresponding base constructor is deleted or if a defaulted default constructor would be deleted (except that the construction of the base whose constructor is being inherited doesn't count). An inheriting constructor cannot be explicitly instantiated or explicitly specialized.
If two using-declarations inherit the constructor with the same signature (from two direct base classes), the program is ill-formed.
(since C++11)
(until C++17)
If the using-declaration refers to a constructor of a direct base of the class being defined (e.g. using Base::Base;), all constructors of that base (ignoring member access) are made visible to overload resolution when initializing the derived class.
If overload resolution selects an inherited constructor, it is accessible if it would be accessible when used to construct an object of the corresponding base class: the accessibility of the using-declaration that introduced it is ignored.
If overload resolution selects one of the inherited constructors when initializing an object of such derived class, then the Base subobject from which the constructor was inherited is initialized using the inherited constructor, and all other bases and members of Derived are initialized as if by the defaulted default constructor (default member initializers are used if provided, otherwise default initialization takes place). The entire initialization is treated as a single function call: initialization of the parameters of the inherited constructor is sequenced-before initialization of any base or member of the derived object.
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
struct B1 {  B1(int, ...) { } };
struct B2 {  B2(double)   { } };
 
int get();
 
struct D1 : B1 {
  using B1::B1;  // inherits B1(int, ...)
  int x;
  int y = get();
};
 
void test() {
  D1 d(2, 3, 4); // OK: B1 is initialized by calling B1(2, 3, 4),
                 // then d.x is default-initialized (no initialization is performed),
                 // then d.y is initialized by calling get()
  D1 e;          // Error: D1 has no default constructor
}
 
struct D2 : B2 {
  using B2::B2; // inherits B2(double)
  B1 b;
};
 
D2 f(1.0);       // error: B1 has no default constructor
struct W { W(int); };
struct X : virtual W {
 using W::W;   // inherits W(int)
 X() = delete;
};
struct Y : X {
 using X::X;
};
struct Z : Y, virtual W {
  using Y::Y;
};
Z z(0); // OK: initialization of Y does not invoke default constructor of X
If the constructor was inherited from multiple base class subobjects of type B, the program is ill-formed, similar to multiply-inherited non-static member functions:
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
struct A { A(int); };
struct B : A { using A::A; };
struct C1 : B { using B::B; };
struct C2 : B { using B::B; };
 
struct D1 : C1, C2 {
  using C1::C1;
  using C2::C2;
};
D1 d1(0); // ill-formed: constructor inherited from different B base subobjects
 
struct V1 : virtual B { using B::B; };
struct V2 : virtual B { using B::B; };
 
struct D2 : V1, V2 {
  using V1::V1;
  using V2::V2;
};
D2 d2(0); // OK: there is only one B subobject.
          // This initializes the virtual B base class,
          //  which initializes the A base class
          // then initializes the V1 and V2 base classes
          //  as if by a defaulted default constructor
As with using-declarations for any other non-static member functions, if an inherited constructor matches the signature of one of the constructors of Derived, it is hidden from lookup by the version found in Derived. If one of the inherited constructors of Base happens to have the signature that matches a copy/move constructor of the Derived, it does not prevent implicit generation of Derived copy/move constructor (which then hides the inherited version, similar to using operator=).
C++
1
2
3
4
5
6
7
8
9
struct B1 {   B1(int); };
struct B2 {   B2(int); };
 
struct D2 : B1, B2 {
  using B1::B1;
  using B2::B2;
  D2(int);   // OK: D2::D2(int) hides both B1::B1(int) and B2::B2(int)
};
D2 d2(0);    // calls D2::D2(int)
0
 Аватар для eXPonent
99 / 52 / 27
Регистрация: 21.05.2012
Сообщений: 1,170
28.02.2017, 16:40  [ТС]
Написал (С++2010):
C++
1
2
3
4
5
6
7
8
9
10
11
class MyIfstream:public ifstream
{
    using ifstream::ifstream;
    public:
        bool Str(const char *s);
};
bool MyIfstream::Str(const char *s)
{
        char buff[12];
        return !(this->get(buff, 12) && strcmp(buff,s) && this->ignore(LLONG_MAX,'\n'));
}
вывалило ошибку:
Кликните здесь для просмотра всего текста
Ошибка 1 error C2039: ifstream: не является членом "std::basic_ifstream<_Elem,_Traits>" c:\users\1\desktop\colonization\coloniza tion\colonization.cpp 17 1 Colonization
Ошибка 2 error C2868: std::ifstream: недопустимый синтаксис для "using"-объявления; требуется полное имя c:\users\1\desktop\colonization\coloniza tion\colonization.cpp 17 1 Colonization
3 IntelliSense: class "std::basic_ifstream<char, std::char_traits<char>>" не содержит члена "ifstream" c:\users\1\desktop\colonization\coloniza tion\colonization.cpp 17 18 Colonization
0
Любитель чаепитий
 Аватар для GbaLog-
3745 / 1801 / 566
Регистрация: 24.08.2014
Сообщений: 6,020
Записей в блоге: 1
28.02.2017, 18:34
Наследование конструкторов поддерживается с с++11, так что вам просто нужно реализовать соответствующие конструкторы.
0
Форумчанин
Эксперт CЭксперт С++
 Аватар для MrGluck
8216 / 5047 / 1437
Регистрация: 29.11.2010
Сообщений: 13,453
28.02.2017, 18:36
Цитата Сообщение от eXPonent Посмотреть сообщение
С++2010
Нет С++2010
Если вы про версию студии, то наследование конструкторов появилось лишь в 2015 студии
https://msdn.microsoft.com/ru-... 67368.aspx
Пишите ручками
0
 Аватар для eXPonent
99 / 52 / 27
Регистрация: 21.05.2012
Сообщений: 1,170
28.02.2017, 20:20  [ТС]
Т.е. оставляем так?
C++
1
2
3
4
5
bool Str(ifstream &f, const char *s)
{
    char buff[12];
    return !(f.get(buff, 12)&&strcmp(buff,s)&&f.ignore(std::numeric_limits<std::streamsize>::max(),'\n'));
}
Добавлено через 33 секунды
Т.е. оставляем так?
C++
1
2
3
4
5
bool Str(ifstream &f, const char *s)
{
    char buff[12];
    return !(f.get(buff, 12)&&strcmp(buff,s)&&f.ignore(std::numeric_limits<std::streamsize>::max(),'\n'));
}
0
 Аватар для eXPonent
99 / 52 / 27
Регистрация: 21.05.2012
Сообщений: 1,170
10.03.2017, 03:19  [ТС]
Цитата Сообщение от MrGluck Посмотреть сообщение
Пишите ручками
наследование писать ручками?
или оставлять всё как есть?
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
10.03.2017, 03:19
Помогаю со студенческими работами здесь

Добавить дружественную функцию в класс
Есть сделанный класс по условию: Создать класс &quot;шар&quot; по таким условиям: а) его экземпляр содержит размер радиуса. b) его конструктор...

Как добавить дружественную функцию в класс
Написал код, а как добавить функцию friend? #include &lt;iostream&gt; #include &lt;conio.h&gt; #include &lt;stdio.h&gt; using namespace std; ...

Добавить в класс Student функцию-член класса
Добавить в класс Student функцию-член класса, определяющую, получает ли студент стипендию, и в головной программе организовать подсчёт...

Добавить в строковый класс функцию, которая создает строку, содержащую пересечение двух строк
Вот такое задание: Добавить в строковый класс функцию, которая создает строку, содержащую пересечение двух строк, то есть общие символы...

Мне нужно ввести в программу данные с помощью ifstream и добавить их всех в вектор чтобы был список.
Доброго времени суток. У меня есть класс Студенты. Мне нужно ввести в программу данные о них(ID, имя, фамилия, возраст) с помощью ifstream...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
16
Ответ Создать тему
Новые блоги и статьи
SDL3 для Web (WebAssembly): Реализация движения на Box2D v3 - трение и коллизии с повёрнутыми стенами
8Observer8 20.02.2026
Содержание блога Box2D позволяет легко создать главного героя, который не проходит сквозь стены и перемещается с заданным трением о препятствия, которые можно располагать под углом, как верхнее. . .
Конвертировать закладки radiotray-ng в m3u-плейлист
damix 19.02.2026
Это можно сделать скриптом для PowerShell. Использование . \СonvertRadiotrayToM3U. ps1 <path_to_bookmarks. json> Рядом с файлом bookmarks. json появится файл bookmarks. m3u с результатом. # Check if. . .
Семь CDC на одном интерфейсе: 5 U[S]ARTов, 1 CAN и 1 SSI
Eddy_Em 18.02.2026
Постепенно допиливаю свою "многоинтерфейсную плату". Выглядит вот так: https:/ / www. cyberforum. ru/ blog_attachment. php?attachmentid=11617&stc=1&d=1771445347 Основана на STM32F303RBT6. На борту пять. . .
Камера Toupcam IUA500KMA
Eddy_Em 12.02.2026
Т. к. у всяких "хикроботов" слишком уж мелкий пиксель, для подсмотра в ESPriF они вообще плохо годятся: уже 14 величину можно рассмотреть еле-еле лишь на экспозициях под 3 секунды (а то и больше),. . .
И ясному Солнцу
zbw 12.02.2026
И ясному Солнцу, и светлой Луне. В мире покоя нет и люди не могут жить в тишине. А жить им немного лет.
«Знание-Сила»
zbw 12.02.2026
«Знание-Сила» «Время-Деньги» «Деньги -Пуля»
SDL3 для Web (WebAssembly): Подключение Box2D v3, физика и отрисовка коллайдеров
8Observer8 12.02.2026
Содержание блога Box2D - это библиотека для 2D физики для анимаций и игр. С её помощью можно определять были ли коллизии между конкретными объектами и вызывать обработчики событий столкновения. . . .
SDL3 для Web (WebAssembly): Загрузка PNG с прозрачным фоном с помощью SDL_LoadPNG (без SDL3_image)
8Observer8 11.02.2026
Содержание блога Библиотека SDL3 содержит встроенные инструменты для базовой работы с изображениями - без использования библиотеки SDL3_image. Пошагово создадим проект для загрузки изображения. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru