Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C++ For Dummies (2004) [eng].pdf
Скачиваний:
84
Добавлен:
16.08.2013
Размер:
8.09 Mб
Скачать

232 Part III: Introduction to Classes

protected: int value;

};

class Student

{

public:

Student(char *pName = “no name”, int ssId = 0) : id(ssId)

{

cout << “constructing student “ << pName << endl; strncpy(name, pName, MAXNAMESIZE); name[MAXNAMESIZE - 1] = ‘\0’;

}

protected:

char name[40]; StudentId id;

};

int main(int argcs, char* pArgs[])

{

Student s(“Chester”, 1234);

cout << “This message from main” << endl;

//wait until user is ready before terminating program

//to allow the user to see the program results system(“PAUSE”);

return 0;

}

Notice in particular the first line of the constructor. Here’s something you haven’t seen before. The : means that what follows are calls to the construc­ tors of data members of the current class. To the C++ compiler, this line reads: “Construct the member id using the argument ssId of the Student constructor. Whatever data members are not called out in this fashion are constructed using the default constructor.”

This new program generates the expected result:

assigning student id 1234 constructing student Chester

This message from main

Press any key to continue . . .

Constructing a constant data member

A problem also arises when initializing a member that has been declared const. Remember that a const variable is initialized when it is declared and cannot