成员对象
成员对象:当一个类的成员是另一个类的对象时,这个对象就叫成员对象。
我们知道,继承满足的关系是:is a关系,而成员对象满足的关系是has a关系,比如学生类和分数类,显然学生有分数,所以分数类可以作为学生类的成员对象
成员对象的构造与析构
1、出现成员对象时,如果成员对象的构造函数是有参构造函数,则该类的初始化列表需要对成员对象进行初始化。class
Member {
private:
int i;
public:
Member(int i)
{
this->i = i;
} }; class Test {
private:
Member member;
public:
Test(): member(1)
{
} };
2、一个含有成员对象的类实例化时要先调用成员对象的构造函数,然后再调用该类的构造函数,析构时先调用该类的析构函数,再调用成员对象的析构函数。
3.如果你将成员对象分数设为私有,那么就不能通过student.fenshu.getfenshu()这种实例化fenshu的方式来访问getfenshu()函数(即成员对象的函数),因为成员对象分数为私有,就不能实例化来访问它,所以student.fenshu就是错的。但是既然成员对象分数为私有,我们就可以在student中建一个接口函数show_stu_fenshu来直接访问fenshu.getfenshu()。
举例:
void Student::show_stu_fenshu()
{
this->stu.show_name(); //通过this先直接访问类对象成员stu,再访问stu的成员函数show_name()
}
school.h:
#ifndef SCHOOL_H
#define SCHOOL_H
#include <student.h>
#include <string>
#include <iostream>
using namespace std;
class School
{
private:
string name;
Student stu;
public:
School();
School(string a);
void show_stu_name();
};
#endif // SCHOOL_H
school.cpp:
#include "school.h"
using namespace std;
School::School()
{
this->name = "none";
cout << "this is default constructor of school" << endl;
}
School::School(string a):stu("zouxu",666)
{
this->name = a;
cout << "this is hancan constructor of school" << endl;
}
void School::show_stu_name()
{
this->stu.show_name();
}
student.h:
#ifndef STUDENT_H
#define STUDENT_H
#include <string>
#include <iostream>
using namespace std;
class Student
{
private:
string name;
int age;
public:
Student();
Student(string a ,int b);
void show_name() const;
void show_age() const;
};
#endif
student.cpp:
#include "student.h"
#include <iostream>
using namespace std;
Student::Student()
{
this->name = "none";
this->age = 0;
cout << "this is default constructor of student" << endl;
}
Student::Student(string a,int b)
{
this->name = a;
this->age = b;
cout << "this is hancan constructor of student" << endl;
}
void Student::show_name() const
{
cout << this->name << endl;
}
void Student::show_age() const
{
cout << this->age << endl;
}
main.cpp:
#include <iostream>
#include <student.h>
#include <school.h>
#include <string.h>
using namespace std;
int main()
{
School school("mianzhong");
//school.stu.show_name(); it is wrong
school.show_stu_name();
return 0;
}