先提出问题:
看着乌漆嘛黑的代码,我的脑子在想运行结果为什么不是两“大”次复制构造函数,因为我认为传入参数这是第一步会调用复制构造函数,但是把参数赋值给类的实例对象的数据成员这也应该是复制构造函数啊。(这可是我花了几个小时才验证到的结果啊)
这是两种不同的写法的不同输出:
如果是初始化列表,我们就会调用三次复制构造函数。
如果是简单的赋值,我们就会调用三次构造函数。
#include <iostream>
using namespace std;
class CPU
{
public:
CPU (){cout<<"创建了CPU"<<endl;}
CPU(const CPU&other){
cout<<"复制一份CPU"<<endl;
}
~CPU () {cout<<"析构了CPU"<<endl;}
void Run() {cout << "CPU开始运行!" << endl; }
void Stop() {cout << "CPU停止运行!" << endl; }
};
class RAM
{
public:
RAM () {cout<<"创建了RAM"<<endl;}
RAM(const RAM&other){
cout<<"复制一份RAM"<<endl;
}
~RAM () {cout<<"析构了RAM"<<endl;}
void Run() {cout << "RAM开始运行!" << endl; }
void Stop() {cout << "RAM停止运行!" << endl; }
};
class CDROM
{
public:
CDROM () {cout<<"创建了CDROM"<<endl;}
CDROM(const CDROM&other){
cout<<"复制一份CDROM"<<endl;
}
~CDROM () {cout<<"析构了CDROM"<<endl;}
void Run() {cout << "CDROM开始运行!" << endl; }
void Stop() {cout << "CDROM停止运行!" << endl; }
};
class Computer
{
private:
CPU cpu;
RAM ram;
CDROM cdrom;
public:
Computer (CPU c, RAM r, CDROM cd)
{
cpu = c;
ram = r;
cdrom = cd;
cout << "构造了一个Computer!" << endl;
}
~Computer () {cout << "析构了一个Computer!"<<endl; }
CPU GetCPU() const { return cpu; }
RAM GetRAM() const { return ram; }
CDROM GetCDROM() const {return cdrom; }
void setCPU(CPU c) { cpu = c; }
void setRAM(RAM r) { ram = r; }
void setCDROM(CDROM cd) { cdrom = cd; }
void Run() {
cout << "Computer开始运行!" << endl;
/********** Begin **********/
cpu.Run();
ram.Run();
cdrom.Run();
/********** End **********/
}
void Stop () {
cout << "Computer停止运行!" << endl;
/********** Begin **********/
cpu.Stop();
ram.Stop();
cdrom.Stop();
/********** End **********/
}
};
int main() {
CPU c1;
RAM r1;
CDROM cd1;
Computer computer(c1, r1, cd1);
computer.Run();
computer.Stop();
}
标签:初始化,调用,列表,复制,赋值,CPU,构造函数
From: https://blog.csdn.net/2301_79982845/article/details/144630307