简体   繁体   English

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

[英]Why the copy constructor called, when I return just a reference of the object c++

It is the code which I cannot figure out why it is not working the way I want, I look around the internet, but did not some good solution. 这是我无法弄清楚为什么它无法按我想要的方式工作的代码,我环顾互联网,但没有找到很好的解决方案。

Point class: 点类:

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;
};

Circle class: 圈子课程:

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; }
};

The usage: 用法:

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;
}

In the following line: 在以下行中:

Point p1 = c.getLocation();

p1 is not a reference, so basically you're copying the referenced object returned by getLocation() , thus calling copy constructor. p1不是引用,因此基本上您是在复制getLocation()返回的引用对象,从而调用复制构造函数。

A solution would be to declare p1 as a reference like this: 一种解决方案是将p1声明为像这样的引用:

Point& p1 = c.getLocation();

暂无
暂无

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

相关问题 类对象的C ++参考返回-为什么不调用复制构造函数? - C++ reference return of class object-why copy constructor not called? 什么时候在c ++中调用了副本构造函数,当我将一个对象分配给另一个对象时不调用它吗? - When is a copy constructor called in c++, is not it called when I assign a object to another object? 当对象包含在c ++中的另一个对象中时,为什么复制构造函数被调用两次? - why the copy constructor is called twice when the object is contained in another object in c++? 什么时候在C ++中调用复制构造函数? -函数返回 - When is a copy constructor called in C++? - Function return 当从 function 返回 object 时,会调用 C++ 中的复制构造函数? - Copy Constructor in C++ is called when object is returned from a function? 返回时调用的C ++拷贝构造函数 - C++ copy constructor called at return 为什么复制构造函数被调用,即使我实际上是在C ++中复制到已经创建的对象? - why copy constructor is getting called even though I am actually copying to already created object in C++? C ++为什么复制构造函数被调用? - C++ Why was the copy constructor called? 当我添加一个不同的对象作为复制构造函数的参数时,为什么调用复制构造函数? - Why the copy constructor is called when I add a different object which is an argument in copy constructor? C ++模板构造函数,为什么要调用拷贝构造函数? - C++ Template constructor, why is copy constructor being called?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM