对象成员
如果一个类的对象是另一个类的数据成员,则称这样的数据成员为对象成员
class A
{
//...
};
class B
{
A a; //类A的对象a为类B的对象成员
public:
//...
};
对象成员的初始化
-
Example 1. 形参表定义
#include <iostream> using namespace std; class A { private: int x; float y; public: A(int x1, float y1) { x = x1; y = y1; } void show() { cout << "x=" << x << endl << "y=" << y << endl; } }; class B { private: A a; int z; public: B(int x1, float y1, int z1) : a(x1, y1) { z = z1; } void show() { a.show(); cout << "z=" << z << endl; } }; int main() { B b(11, 22, 33); b.show(); return 0; }
-
Example 2. 另一种定义
#include <iostream> using namespace std; class A { private: int x; float y; public: A(int x1, float y1) { x = x1; y = y1; } void show() { cout << "x=" << x << endl << "y=" << y << endl; } }; class B { private: A a; int z; public: B(A a1, int z1) : a(a1) { z = z1; } void show() { a.show(); cout << "z=" << z << endl; } }; int main() { A a(11, 22); B b(a, 33); b.show(); return 0; }
Example 3.
#include <iostream>
#include <string.h>
using namespace std;
class score
{
private:
float computer;
float english;
float mathematics;
public:
score(float c, float e, float m)
{
computer = c;
english = e;
mathematics = m;
}
score() { computer = english = mathematics = 0; }
void show()
{
cout << "score computer: " << computer << endl
<< "score english: " << english << endl
<< "score mathematics: " << mathematics << endl;
}
void modify(float c, float e, float m)
{
computer = c;
english = e;
mathematics = m;
}
};
class student
{
private:
char *name;
char *stu_no;
score score1;
public:
student(char *name1, char *stu_no1, float s1, float s2, float s3) : score1(s1, s2, s3)
{
name = new char[strlen(name1) + 1];
strcpy(name, name1);
stu_no = new char[strlen(stu_no1) + 1];
strcpy(stu_no, stu_no1);
}
~student()
{
delete[] name;
delete[] stu_no;
}
void modify(char *name1, char *stu_no1, float s1, float s2, float s3)
{
delete[] name;
name = new char[strlen(name1) + 1];
strcpy(name, name1);
delete[] stu_no;
stu_no = new char[strlen(stu_no1) + 1];
strcpy(stu_no, stu_no1);
score1.modify(s1, s2, s3);
}
void show()
{
cout << "name: " << name << endl
<< "stu_no: " << stu_no << endl;
score1.show();
}
};
int main()
{
student stu1("Li Ming", "990201", 90, 85, 88);
stu1.show();
cout << endl;
stu1.modify("Zhao Hao", "990203", 95, 81, 79);
stu1.show();
return 0;
}
/*
name: Li Ming
stu_no: 990201
score computer: 90
score english: 85
score mathematics: 88
name: Zhao Hao
stu_no: 990203
score computer: 95
score english: 81
score mathematics: 79
*/