gpt4 book ai didi

c++ - 为什么做赋值不会使对象指向同一位置

转载 作者:行者123 更新时间:2023-11-30 01:48:36 26 4
gpt4 key购买 nike

我正在尝试理解复制构造函数的概念。使用复制构造函数,我得到了想要的结果。但是没有复制构造函数,我得到了相同的结果。代码在这里:

#include<iostream>
using namespace std;

class Point
{
private:
int x, y;
public:
Point(int x1, int y1) { x = x1; y = y1; }

// Copy constructor
// Point(const Point &p2) {x = p2.x; y = p2.y; }
void set()
{
x=50;
y = 100;
}
int getX() { return x; }
int getY() { return y; }
};

int main()
{
Point p1(10, 15); // Normal constructor is called here
Point p2 = p1 ;
// p2 = p1;
cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
cout << "\np2.x = " << p2.getX() << ", p2.y = " << p2.getY();
p2.set();
cout << "\np1.x = " << p1.getX() << ", p1.y = " << p1.getY();
cout << "\np2.x = " << p2.getX() << ", p2.y = " << p2.getY();
// Copy constructor is called here

// Let us access values assigned by constructors
return 0;
}

输出是:

p1.x = 10, p1.y = 15
p2.x = 10, p2.y = 15
p1.x = 10, p1.y = 15
p2.x = 50, p2.y = 100

不应该是:

p1.x = 10, p1.y = 15
p2.x = 10, p2.y = 15
p1.x = 50, p1.y = 100
p2.x = 50, p2.y = 100

编辑 1:如果我像这样初始化对象会怎样:

Point p1(10, 15); // Normal constructor is called here
Point p2(11,10);
p2 = p1;

它会调用拷贝构造函数吗?如果不是,为什么在这种情况下结果是相同的?

最佳答案

C++ 对对象的对象引用 进行了区分。如果你想

p2p1 指向同一个Point,你应该这样做:

Point& p2 = p1;

因为您从未为您的 Point 类定义复制构造函数,所以编译器给了您一个。它实际上看起来像这样:

Point(const Point& other) : x(other.x), y(other.y)
{}

而你的代码,Point p2 = p1 将调用这个复制构造函数。

这会导致整数值被复制,而不是指向内存中的相同位置。

关于c++ - 为什么做赋值不会使对象指向同一位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30265265/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com