将VS2013 更新为VS2019会导致左值错误,想知道原因

Updating VS2013 to VS2019 causes Lvalue error, would like to understand why

本文关键字:错误 想知道 更新 VS2013 VS2019      更新时间:2023-10-16

编辑:这不是一个重复的问题。人们将我的问题混淆为"为什么我的代码不起作用",但事实并非如此,而是"为什么它在VS 2013而不是2019上工作",并且已经得到了回答。这不是一个重复的问题。我多次问为什么它在 2013 年而不是 2019 年有效。

所以我正在创建一个DLL,并决定从VS2013升级到VS2019,这样我就可以获得最新的Visual Studio包和最新的IDE。 升级后突然出现了一个错误:initial value of reference to non-const must be an lvalue自从这个错误以来,我终于设法修复了它,但我想了解为什么会发生此错误,尤其是在升级到不同版本的 Visual Studio 之后。

简而言之,在 Visual Studio 2013 中工作的代码是一个矢量结构,具有成员函数和运算符重载,如下所示:

页眉

struct Vec2 {
float x, y;
/* Insert other obligatory code */
Vec2 add(const Vec2);
Vec2 &operator+(const Vec2);
}

实现

Vec2 Vec2::add(const Vec2 o) {
return {
x + o.x,
y + o.y
};
}
Vec2 &Vec2::operator+(const Vec2 o) {
return add(o); // <-- 'initial value of reference to non-const must be an lvalue'
}

就像我之前说的,这段代码可以完美地工作和编译。升级后,当它到达我的重载加运算符函数中的return add(o);时,它会抛出前面提到的错误。

我只是想知道为什么在我升级后开始发生这种情况......MSVC 编译器中是否发生了更改?

我确实修复了它,这是我的解决方案,但我担心它可能效率低下......

新页眉

struct Vec2 {
/* yada yada */
Vec2 &add(const Vec2);
Vec2 &operator+(const Vec2);
}

新实施

Vec2 &Vec2::add(const Vec2 o) {
Vec2 v(x + o.x, y + o.y); // Just normal constructor
return v;
}
Vec2 &Vec2::operator+(const Vec2 o) {
return add(o); 
}

任何分享的知识将不胜感激,如果有更好,更快和/或更容易的解决方案,请告诉我! :)

这些成员函数的声明和定义不正确

Vec2 add(const Vec2);
Vec2 &operator+(const Vec2);

例如,在第一个函数中,参数声明中的限定符const是多余的。函数应使用限定符 const 声明,因为它们不会更改原始向量。

在第二个函数中,您将返回对临时对象的引用。

可以通过以下方式声明和定义函数

struct Vec2 {
float x, y;
/* Insert other obligatory code */
Vec2 add(const Vec2 &) const;
Vec2 operator+(const Vec2 & ) const;
};
Vec2 Vec2::add(const Vec2 &o) const {
return {
x + o.x,
y + o.y
};
}
Vec2 Vec2::operator+(const Vec2 &o) const {
return add(o); 
}

这是一个演示程序

#include <iostream>
struct Vec2 {
float x, y;
/* Insert other obligatory code */
Vec2 add(const Vec2 &) const;
Vec2 operator+(const Vec2 & ) const;
};
Vec2 Vec2::add(const Vec2 &o) const {
return {
x + o.x,
y + o.y
};
}
Vec2 Vec2::operator+(const Vec2 &o) const {
return add(o); 
}
int main() 
{
Vec2 v1 = { 10, 10 };
Vec2 v2 = { 20, 20 };
Vec2 v3 = v1 + v2;
std::cout << v3.x << ' ' << v3.y << 'n';
v3 = v3.add( v3 );
std::cout << v3.x << ' ' << v3.y << 'n';
return 0;
}

它的输出是

30 30
60 60
相关文章: