繁体   English   中英

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

[英]Why the copy constructor called, when I return just a reference of the object 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;
}

在以下行中:

Point p1 = c.getLocation();

p1不是引用,因此基本上您是在复制getLocation()返回的引用对象,从而调用复制构造函数。

一种解决方案是将p1声明为像这样的引用:

Point& p1 = c.getLocation();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM