为什么复制构造函数被调用,当我只返回对象c ++的引用时

时间:2017-05-12 06:35:32

标签: c++

这是我无法弄清楚为什么它不按照我想要的方式工作的代码,我环顾互联网,但没有一些好的解决方案。

点类:

class Point
{
public:
    Point(const Point &) {
        cout << "copy constructor was called" << endl;
    }
    Point(int x, int y) : x(x), y(y) {
    }
    void setX(int x) {this->x = x;}
    void setY(int y) {this->y = y;}
    int getX() const { return x; }
    int getY() const  { return y; }
private:
    int x;
    int y;
};

圈子类:

class Circle
{
private:
    int rad;
    Point &location;
public:
    Circle(int radius, Point &location) : rad(radius), location(location) {}
    int getRad() { return rad; }
    Point & getLocation() { return location; }
};

用法:

int main() {
    Point p(23, 23);
    Circle c(12, p);

    Point p1 = c.getLocation();
    p1.setX(200);

    cout << p.getX() << endl; // prints 23, which I want to be 200
                              // copy constructor was called

    system("pause");
    return 0;
}

1 个答案:

答案 0 :(得分:4)

在以下行中:

Point p1 = c.getLocation();

p1不是引用,所以基本上你要复制getLocation()返回的引用对象,从而调用copy构造函数。

解决方案是将p1声明为这样的参考:

Point& p1 = c.getLocation();