Чтение онлайн

ЖАНРЫ

Освой самостоятельно С++ за 21 день.

Либерти Джесс

Шрифт:

26: // static int ConstructorCount:

27:

28: private:

29: String (int); // закрытый конструктор

30: char * itsString;

31: unsigned short itslen;

32:

33: };

34:

35: ostream& operator<<( ostream& theStream,String& theStnng)

36: {

37: theStream << theString.GetString;

38: return theStream;

39: }

40:

41: istream& operator>>( istream& theStream,String& theString)

42: {

43: theStream >> theString.GetString;

44: return theStream;

45: }

46:

47: int main

48: {

49: StringtheString("npHBeT,

мир.");

50: cout << theString;

51: return 0;

52: }

5. Жучки: что неправильно в этой программе?

1: #include <iostrearm.h>

2:

3: class Animal;

4:

5: void setValue(Animal& , int);

6:

7:

8: class Animal

9: {

10: public:

11: int GetWeightconst { return itsWeight; }

12: int GetAge const { return itsAge; }

13: private:

14: int itsWeight;

15: int itsAge;

16: };

17:

18: void setValue(Animal& theAnimal, int theWeight)

19: {

20: friend class Animal;

21: theAnimalitsWeight = theWeight;

22: }

23:

24: int main

25: {

26: Animal peppy;

27: setValue(peppy,5):

28: return 0;

29: }

Нельзя помещать объявление friend в функцию. Нужно объявить функцию другом в объявлении класса.

6. Исправьте листинг, приведенный в упражнении 5, и откомпилируйте его.

1: #include <iostream.h>

2:

3: class Animal;

4:

5: void setValue(Animal& , int);

6:

7:

8: class Animal

9: {

10: public:

11: friend void setValue(Animal&, int);

12: int GetWeightconst { return itsWeight; }

13: int GetAge const { return itsAge; }

14: private:

15: int itsWeight;

16: int itsAge;

17: };

18:

19: void setValue(Animal& theAnimal, int theWeight)

20: {

21: theAnimal.itsWeight = theWeight;

22: }

23:

24: int main

25: {

26: Animal peppy;

27: setValue(peppy,5);

28: return 0;

29: }

7. Жучки: что неправильно в этой программе?

1: #include <iostream.h>

2:

3: class Animal;

4:

5: void setValue(Animal& , int):

6: void setValue(Animal& , int.int);

7:

8: class Animal

9: {

10: friend void setValue(Animal& ,int):

11: private:

12: mt itsWeight;

13: int itsAge;

14: };

15:

16: void setValue(Animal& theAnimal, int theWeight)

17: {

18: theAnimal.itsWeight = theWeight;

19: }

20:

21:

22: void setValue(Animal& theAnimal, int theWeight, int theAge)

23: {

24: theAnimal.itsWeight = theWeight:

25: theAnimal.itsAge = theAge;

26: }

27:

28: int main

29: {

30: Animal peppy;

31: setValue(peppy,5);

32: setValue(peppy,7,9);

33: return 0:

34: }

Функиия setValue(Animal& ,int)

была объявлена дружественной, но перегруженная

функция setValue(Animal& ,int,int) не была объявленадружественной.

8. Исправьте листинг, приведенный в упражнении 7, и откомпилируйте его.

1: #include <iostream.h>

2:

3: class Animal;

4:

5: void setValue(Animal& , int);

6: void setValue(Animal& , int.int);

7:

8: class Animal

9: {

10: friend void setValue(Animal& ,int);

11: friend void setValue(Animal& ,int.int): // изменение!

12: private:

13: int itsWeight;

14: int itsAge;

15: };

16:

17: void setValue(Animal& theAnimal, int theWeight)

18: {

19: theAnimal.itsWeight = theWeight;

20: }

21:

22:

23: void setValue(Animal& theAnimal, int theWeight, int theAge)

24: {

25: theAnimal.itsWeight = theWeight;

26: theAnimal.itsAge = theAge;

27: }

28:

29: int main

30: {

31: Animal peppy;

32: setValue(peppy.5);

33: setValue(peppy,7,9);

34: return 0;

35: } 

День 16

Контрольные вопросы 

1. Что такое оператор ввода и как он работает?

Оператор ввода (>>) является членом объекта istream и используется для записи данных в переменные программы.

2. Что такое оператор вывода и как он работает?

Оператор вывода (<<)является членом объекта ostream и используется для записи данных в устройство вывода.

3. Перечислите три варианта перегруженной функции cin.get и укажите основные их отличия.

Первый вариант функции-члена get используется без параметров. Она возвращает значение считанного символа. При достижении кониа файла она возвратит EOF (end of file, т.е. конец файла).

Второй вариант функции-члена cin.get принимает в качестве параметра ссылку на символьную переменную. Этой переменной присваивается следующий символ в потоке ввода. Возвращаемым значением этой функции является объект iostream.

В третьей, последней версии в функции get устанавливаются массив символов, количество считываемых символов и символ разделения (которым по умолчанию является разрыв строки). Эта версия функции get возвращает символы в массив либо до тех пор, пока не будет введено максимально возможное количество символов, либодо первого символа разрыва строки. Если функция get встречает символ разрыва строки, ввод прерывается, а символ разрыва строки остается в буфере ввода.

Поделиться с друзьями: