【发布时间】:2020-02-28 09:55:39
【问题描述】:
此代码在尝试添加复制构造函数之前有效。
#include <iostream>
#include <string.h>
using namespace std;
class Laptop
{
public:
string brand;
string model;
int ram;
int storage;
Laptop(string brand, string model, int ram, int storage)
{
this->brand = brand;
this->model = model;
this->ram = ram;
this->storage = storage;
}
Laptop(Laptop &x)
{
this->brand = x.brand;
this->model = x.model;
this->ram = x.ram;
this->storage = x.storage;
}
void displayData()
{
cout << brand << " " << model << ": RAM = " << ram << "GB, Storage = " << storage << "GB" << endl;
}
};
int main()
{
Laptop myLaptop = Laptop("Asus", "Zenbook", 16, 2048);
Laptop copyOriginal = Laptop(myLaptop);
copyOriginal.displayData();
return 0;
}
上面的代码不起作用,它只有在我使用这种语法创建myLaptop 和oldLaptop 时才起作用:
Laptop myLaptop("Asus", "Zenbook", 16, 2048);
Laptop copyOriginal(myLaptop);
【问题讨论】:
标签: c++ class reference constants copy-constructor