【C++第二阶段】类对象作为成员属性

你好你好!
以下内容仅为当前认识,可能有不足之处,欢迎讨论!



类对象作为成员属性

①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类再释放。

运行结果:

image-20240203155907244

以上运行结果验证①②理论。


以上是我的学习笔记,希望对你有所帮助!
如有不当之处欢迎指出!谢谢!

学吧,学无止境,太深了

  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

HelpFireCode

随缘惜缘不攀缘。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值