C++ 初始化对象中的对象、引用、常量

钱能C++ P280~P283


#include <iostream.h>
#include <string.h>

class StudentID
{
public:
StudentID(int id = 0)
{
value = id;
cout << "StudentID 构造时 id " << value << endl;
}

~StudentID()
{
cout << "StudentID 析构时 id " << value << endl;
}

int value;
};

class Student
{
public:
Student(char *pName="noName", int ssID = 0)
{
cout << "Student 构造时 pName " << pName << endl;
strcpy(name,pName);
name[sizeof(name) - 1] = '\0';
StudentID id(ssID);
}

~Student()
{
cout << "Student 析构" << endl;
}

char name[20];
StudentID id; // 从输出可以看出,StudentID初始化了两次
// 首先初始化这里,再到构造方法
};


int main()
{
Student s("Tom",1988);
return 0;
}



StudentID 构造时 id 0
Student 构造时 pName Tom
StudentID 构造时 id 1988
StudentID 析构时 id 1988
Student 析构
StudentID 析构时 id 0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值