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

标签 c++ initialization copy-constructor

<分区>

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

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
}

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

最佳答案

在第二种情况下,使用赋值运算符代替复制构造函数。构造函数仅在初始化对象时使用。

您还可以重载赋值运算符。你可以这样做:

Test& operator=(const Test &rhs);

关于c++ - 复制构造函数。有用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32428110/

相关文章:

c++ - 每次循环初始化一个 vector

C++ 问题在同一行上声明多个对象实例

C:动态分配时通过引用传递

c++ - 从指向基类的指针调用派生类的复制构造?

c++ - 检测 CPU 架构编译时

c++ - 使用 <name> = ... 不命名类型

c# - 是否应该将此列表初始值设定项行为报告为 Visual Studio C# 编译器中的错误?

c++ - 以对象为参数的构造函数

c++ - 了解 C++ 中的复制构造函数

C++0x、编译器钩子(Hook)和硬编码语言特性