将VS2013 更新为VS2019会导致左值错误,想知道原因
Updating VS2013 to VS2019 causes Lvalue error, would like to understand why
编辑:这不是一个重复的问题。人们将我的问题混淆为"为什么我的代码不起作用",但事实并非如此,而是"为什么它在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
- 我想知道长双倍和双倍之间的区别
- 我是 C++ 的初学者,我想知道如何在 2D 矢量中获取重复值
- C++新手,想知道如何使用VS code 2019播放音频文件
- 我是C++新手,我想知道,为什么在c ++中使用纯虚函数?为什么要使用纯虚函数?
- 我想知道为什么"std::unique_ptr<int> foo(新 int)"是合法的,因为"std::<int>unique_ptr"要求输入参数类型应该是"int"?
- 我想知道我是否可以将一个类分配给特定的成员数据并创建该类的实例
- 我想知道变焦和轨道在哪里出了问题
- 我创建了一个库,想知道设计是否效率低下
- 想知道我哪里错了
- 我想知道我将如何实现 + 运算符重载.我已经从我上一个问题中计算出 += 运算符重载
- 将VS2013 更新为VS2019会导致左值错误,想知道原因
- 我想知道如何将所有数值与没有任何空格的字符串分开,就像 123we45rt75 一样
- 合成错误不知道为什么会发生这种情况,请检查一下并告诉我这是我的编码还是视觉工作室
- 我想知道在构造函数中初始化变量时的生命周期
- 我想知道像素/片段的原始模板值.零还是一个?如果可能的话,以获取哪些特定操作会修改模板值
- 在Visual Studio 2013中编译的STL列表代码在Visual Studio 2019中给出了错误.想知道原
- VS为我提供了对构造函数的另一个解决方案,但我想知道为什么我的工作不起作用
- 我想知道下面的指针等同于做什么
- 语法错误,也想知道我是否可以使这段代码更有效率
- 嗨,我只是想知道这个错误意味着什么.当我尝试构建时,