赋值运算符的奇怪行为

时间:2018-09-13 11:12:02

标签: c++ xcode copy-constructor assignment-operator

我的课程如下:

class Point {
public:
    Point() { cout << "\nDefault Constructor called"; }
    Point(const Point &t) { cout << "\nCopy constructor called"; }
};

,并且在someFunction()中,我正在尝试

void someFunction()
{
    Point *t1, *t2;
    t1 = new Point();
    t2 = new Point(*t1);
    Point t3 = *t1;
    Point t4;
    t4 = t3;
    t4 = *t1;
    t4 = t3;
}

我面临的问题是最后三行代码未得到执行。即使在调试Xcode时,控制流也直接来自Point t4; 到代码末尾。 为什么在这里Point t3 = *t1;

中没有调用构造函数

1 个答案:

答案 0 :(得分:2)

The enum is: MyEnum.Bar是分配,而不是初始化。您需要赋值运算符t4 = t3;来查看输出,否则它将使用默认的赋值运算符,在您的情况下不执行任何操作:

Point & operator=(const Point&t)

输出:

#include <iostream>
using namespace std;
class Point {
public:
    Point() { cout << "\nNormal Constructor called"; }
    Point(const Point &t) { cout << "\nCopy constructor called"; }
    Point & operator=(const Point&t) { cout << "\nAssignment"; return *this;}
};
int main() {
    Point *t1, *t2;
    t1 = new Point();
    t2 = new Point(*t1);
    Point t3 = *t1;
    Point t4;
    t4 = t3;
    t4 = *t1;
    t4 = t3;
    return 0;
}

https://ideone.com/Za6lkL