提问人:davylang 提问时间:9/8/2020 最后编辑:davylang 更新时间:9/8/2020 访问量:113
C++ 如何使用复制构造函数
C++ how to use a copy constructor
问:
所以我试图在我的主要中创建一个副本,就像这样myCat
#include<iostream>
#include<string>
using namespace std;
class Cat
{
private:
string name;
string breed;
int age;
static constexpr double licenseFee = 10;
public:
void setCatData(string, string, int);
void showCat();
void displayAddress(Cat mycat);
Cat(){
}
Cat(const Cat &aCat) { //copy constructor
name = aCat.name;
breed = aCat.breed;
age = aCat.age;
}
};
void Cat::setCatData(string catName, string catBreed, int catAge)
{
name = catName;
breed = catBreed;
age = catAge;
}
void Cat::showCat()
{
cout << "Cat: " << name << " is a " << breed << endl;
cout << "The cat's age is " << age << endl;
cout << "License fee: $" << licenseFee << endl;
}
void Cat::displayAddress(Cat myCat) {
cout << "The address of the object is: "<< &myCat;
}
int main()
{
Cat myCat;
Cat myCat2 = myCat; //coppy constructor called
cout << "ORIGNAL CAT" << endl;
myCat.setCatData("Tigger", "Fluffy unit", 3);
myCat.showCat();
cout << endl;
//myCat.displayAddress(myCat);
cout << "COPY CAT" << endl;
myCat2.showCat();
}
但是,没有复制任何内容,我的输出就是这样
ORIGNAL CAT
Cat: Tigger is a Fluffy unit
The cat's age is 3
License fee: $10
COPY CAT
Cat: is a
The cat's age is 1
License fee: $10
我不确定为什么 myCat2 不包含相同的数据是 myCat?
答:
3赞
Alan Birtles
9/8/2020
#1
如果希望副本具有与原始对象相同的属性,则需要在修改对象后复制该对象:
Cat myCat;
cout << "ORIGNAL CAT" << endl;
myCat.setCatData("Tigger", "Fluffy unit", 3);
myCat.showCat();
cout << endl;
Cat myCat2 = myCat;
cout << "COPY CAT" << endl;
myCat2.showCat();
评论
0赞
davylang
9/8/2020
天哪,这么简单的错误,但我忽略了它!谢谢
0赞
Harmen
9/8/2020
#2
复制构造函数确实有效,只是在设置数据之前进行复制。 不包含相同的数据,因为它是“默认构造”数据的副本。myCat2
myCat
如果要在改编时进行更改,那么应该是参考,而不是复制。myCat2
myCat
myCat2
(更改了构造函数签名的示例:https://godbolt.org/z/zE9MjK)
评论
Cat(const Cat &Cat)
myCat
myCat2
myCat