C++中组合类的初始化:冒号语法(常数据成员和引用成员的初始化)

2014-11-24 12:34:42 · 作者: · 浏览: 0

//============================================================================

// Name : main.cpp

// Author : ShiGuang

// Version :

// Copyright : sg131971@qq.com

// Description : Hello World in C++, Ansi-style

//============================================================================

#include

#include

using namespace std;

class Student

{

int semesHours;

float gpa;

public:

Student(int i)

{

cout << "constructing student.\n";

semesHours = i;

gpa = 3.5;

}

~Student()

{

cout << "~Student\n";

}

};

class Teacher

{

string name;

public:

Teacher(string p)

{

name = p;

cout << "constructing teacher.\n";

}

~Teacher()

{

cout << "~Teacher\n";

}

};

class TutorPair

{

public:

TutorPair(int i, int j, string p) :

teacher(p), student(j)

{

cout << "constructing tutorpair.\n";

noMeetings = i;

}

~TutorPair()

{

cout << "~TutorPair\n";

}

protected:

Student student;

Teacher teacher;

int noMeetings;

};

int main(int argc, char **argv)

{

TutorPair tp(5, 20, "Jane");

cout << "back in main.\n";

return 0;

}

注意:程序里面的赋值方式,以及构造函数析构函数的调用次序。

constructing student.

constructing teacher.

constructing tutorpair.

back in main.

~TutorPair

~Teacher

~Student

另外:构造函数初始化常数据成员和引用成员。

//============================================================================

// Name : main.cpp

// Author : ShiGuang

// Version :

// Copyright : sg131971@qq.com

// Description : Hello World in C++, Ansi-style

//============================================================================

#include

#include

using namespace std;

class Student

{

public:

Student(int s, int &k) :

i(s), j(k)

{

} //不可以直接赋值

void p()

{

cout << i << endl;

cout << j << endl;

}

protected:

const int i;

int &j;

};

int main(int argc, char **argv)

{

int c = 123;

Student s(9818, c);

s.p();

return 0;

}

9818

123

摘自 sg131971的学习笔记