你好你好!
以下内容仅为当前认识,可能有不足之处,欢迎讨论!
文章目录
类对象作为成员属性
①A类的成员属性可以是另一个类B,与此对应的B类成员属性初始化使用的是隐式调用构造函数。
比如代码:
#include<iostream>
#include<string>
using namespace std;
class Education {
string education_grade;
int education_years;
public:
Education(string grade, int years) {
cout << "=========================" << endl;
cout << "Education有参构造函数调用" << endl;
cout << "=========================" << endl;
education_grade = grade;
education_years = years;
}
~Education() {
cout << "=========================" << endl;
cout << "==Education析构函数调用==" << endl;
cout << "=========================" << endl;
}
string get_education_grade() {
return education_grade;
}
int get_education_years() {
return education_years;
}
};
class Person {
string person_name;
Education person_edu;
public:
Person(string person_name, string person_edu_grade, int person_edu_years) :person_name(person_name), person_edu(person_edu_grade, person_edu_years) {
//这里的person_edu(education) 相当于饮食构造函数调用:Education person_edu = {person_edu_grade, person_edu_years}
cout << "=========================" << endl;
cout << "====Person有参函数调用===" << endl;
cout << "=========================" << endl;
}
~Person() {
cout << "=========================" << endl;
cout << "====Person析构函数调用===" << endl;
cout << "=========================" << endl;
}
void print_ID() {
cout << person_name << "的个人信息:" << endl;
cout << "现在是" << person_edu.get_education_grade() << person_edu.get_education_years() << "年级." << endl;
}
};
void test_020315() {
string name = "张三";
string grade = "大学";
Person person = Person(name, grade, 3);
person.print_ID();
}
int main(){
test_020315();
system("pause");
return 0;
}
②当A类中的成员属性包含一个类时,比如说B类,它们的构造顺序是谁先谁后?析构顺序又是谁先谁后?
构造顺序B类先构造,A类才能构造,同时因为在堆区(不清楚具体原因,暂且先记成这样),A类先析构(释放),B类再释放。
运行结果:
以上运行结果验证①②理论。
以上是我的学习笔记,希望对你有所帮助!
如有不当之处欢迎指出!谢谢!