gpt4 book ai didi

c++ - 复制构造函数。有用

转载 作者:行者123 更新时间:2023-11-28 06:05:50 29 4
gpt4 key购买 nike

<分区>

嘿嘿。我有一个让我很难过的问题。我自定义了一个普通的拷贝构造函数但它只在我初始化一个对象时起作用,但在我想将值复制到现有对象时不起作用。请看:

class Test {
public:
int a;
int b;

Test() {
a=0;
b=0;
} // default constructor

Test(int x,int y): a(x), b(y) {} //constructor number 2

Test(Test & object): a(object.a*2), b(object.b*2) { }

// (i multiply times two to see the difference between
// compilators default copy constructor and my selfdefined - see above)

void show() { //it shows the current value
cout << "a:" << a << endl;
cout << "b:" << b << endl;
}
};

int main() {
Test A(2, 4);
Test B = A; // my copy constructor works **only** while initializing...
B.show(); //...so printed values are as i want: B.a=4 B.b=8...
B = A;//...but now i think my own should be used...
B.show();//... but is not i thought it should be B.a=4 B.b=8 but
//the default compilers copy constructor is used and: B.a=2 B.b=4 as in //object A
}

我有负载的问题,它们比这更复杂,但这是我在这个网站上的第一个问题。请帮助我,我不需要快速解决方案,您可以在答案中写很多。谢谢。

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com