gpt4 book ai didi

C++ 错误 C2440 : 'initializing' : cannot convert from 'class name' to 'same class name'

转载 作者:行者123 更新时间:2023-11-30 03:21:50 24 4
gpt4 key购买 nike

typedef unsigned int uint32_t;
struct Point {
uint32_t x, y;
Point() :x(0), y(0) {}
Point(Point& p) {
x = p.x;
y = p.y;
}
Point operator=(Point& p) {
x = p.x;
y = p.y;
return *this;
}
};
struct Snake {
Point pp;
Point p() { return pp; }
};
int main() {
Snake s;
Point p1;
Point p2 = p1; //ok
Point p3 = s.pp; //ok
Point wtf = s.p(); //error C2440??
}

我试图编译上面的代码并得到这个奇怪的错误:

error C2440: 'initializing': cannot convert from 'Point' to 'Point'

note: Cannot copy construct struct 'Point' due to ambiguous copy constructors or no available copy constructor

我想出了 2 种方法让它起作用:改变

Point p() { return pp; }

进入

Point& p() { return pp; }

或向“Point”添加移动构造函数:

Point(Point&& p) {
x = p.x;
y = p.y;
}

我决定选择第二个选项。但是我发现了一个更奇怪的问题:

我添加了一些“调试代码”:

#include <iostream>
using std::cout;
typedef unsigned int uint32_t;
struct Point {
uint32_t x, y;
Point() :x(0), y(0) {
cout << "\tPoint()\n";
}
Point(Point& p) {
x = p.x;
y = p.y;
cout << "\tPoint(point& p)\n";
}
Point& operator=(Point& p) {
x = p.x;
y = p.y;
cout << "\tPoint& operator=(Point& p)\n";
return *this;
}
Point(Point&& p) {
x = p.x;
y = p.y;
cout << "\tPoint(Point&& p)\n";
}
};
struct Snake {
Point pp;
Point p() { return pp; }
};
int main() {
cout << "Code 0:\n";
Snake s;
cout << "Code 1:\n";
Point p1;
cout << "Code 2:\n";
Point p2 = p1; //ok
cout << "Code 3:\n";
Point p3 = s.pp; //ok
cout << "Code 4:\n";
Point wtf = s.p(); //error C2440??

char c;
std::cin >> c;
}

这给了我:

Code 0:
Point()
Code 1:
Point()
Code 2:
Point(point& p)
Code 3:
Point(point& p)
Code 4:
Point(point& p)

这意味着移动构造函数根本没有被调用。

为什么我的第一个代码不起作用?为什么移动构造函数没有被调用,即使它是解决问题的方法?

(我用的是visual studio 2017)

最佳答案

复制构造函数和复制赋值运算符通过const 引用获取它们的输入参数,但你的都缺少const .

此外,赋值运算符返回 *this引用,但你的按返回。

试试这个:

struct Point {
uint32_t x, y;

Point() : x(0), y(0) {}

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

Point& operator=(const Point& p) {
x = p.x;
y = p.y;
return *this;
}
};

但是请注意,您的结构很简单,因此您应该让编译器为您生成默认的复制构造函数和默认的复制赋值运算符。它的实现足以满足您的示例:

struct Point {
uint32_t x = 0;
uint32_t y = 0;
};

最后,无需手动定义自己的 uint32_t类型。 C++11 有一个标准 uint32_t <cstdint> 中定义的类型 header 。

关于C++ 错误 C2440 : 'initializing' : cannot convert from 'class name' to 'same class name' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51805249/

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