C++ 中的运算符重载:unqualified-id 错误
Operator Overloading in C++: unqualified-id error
我们刚刚开始了解 类 和计算模块中的运算符重载,我对给出的示例之一有疑问:
#include <iostream>
using namespace std;
int main()
{
class PositivePoint
{
// Must return PositivePoint object by value
PositivePoint operator+(const PositivePoint& pSrc);
};
PositivePoint PositivePoint::operator+(const PositivePoint& pSrc)
{
Positive Point ret;
ret.mX = mX + pSrc.mX;
ret.mY = mY + pSrc.mY;
return ret;
}
// Return success
return 0;
}
我一直收到错误“unqualified-id in declaration before '(' token。我不明白为什么会这样,因为我认为在上面的例子中正确定义了运算符重载。
你的代码几乎没问题,至少在运算符的语法上是这样..
您需要将 class 和运算符移出主函数...
定义 mX、My 并更正为 ret
声明的拼写错误
在那之后我测试并工作了...
#include <iostream>
using namespace std;
class PositivePoint {
public:
int mY;
int mX;
// Must return PositivePoint object by value
PositivePoint operator+(const PositivePoint& pSrc);
};
PositivePoint PositivePoint::operator+(const PositivePoint& pSrc) {
PositivePoint ret;
ret.mX = mX + pSrc.mX;
et.mY = mY + pSrc.mY;
return ret;
}
int main() {
PositivePoint a;
a.mX = 1;
a.mY = -2;
PositivePoint b;
b.mX = 3;
b.mY = 5;
PositivePoint c = a + b;
std::cout << "Hello World!"<< std::endl;
std::cout << "c.X: " << c.mX << std::endl;
std::cout << "c.Y: " << c.mY << std::endl;
// your code goes here
return 0;
}
我们刚刚开始了解 类 和计算模块中的运算符重载,我对给出的示例之一有疑问:
#include <iostream>
using namespace std;
int main()
{
class PositivePoint
{
// Must return PositivePoint object by value
PositivePoint operator+(const PositivePoint& pSrc);
};
PositivePoint PositivePoint::operator+(const PositivePoint& pSrc)
{
Positive Point ret;
ret.mX = mX + pSrc.mX;
ret.mY = mY + pSrc.mY;
return ret;
}
// Return success
return 0;
}
我一直收到错误“unqualified-id in declaration before '(' token。我不明白为什么会这样,因为我认为在上面的例子中正确定义了运算符重载。
你的代码几乎没问题,至少在运算符的语法上是这样..
您需要将 class 和运算符移出主函数...
定义 mX、My 并更正为 ret
在那之后我测试并工作了...
#include <iostream>
using namespace std;
class PositivePoint {
public:
int mY;
int mX;
// Must return PositivePoint object by value
PositivePoint operator+(const PositivePoint& pSrc);
};
PositivePoint PositivePoint::operator+(const PositivePoint& pSrc) {
PositivePoint ret;
ret.mX = mX + pSrc.mX;
et.mY = mY + pSrc.mY;
return ret;
}
int main() {
PositivePoint a;
a.mX = 1;
a.mY = -2;
PositivePoint b;
b.mX = 3;
b.mY = 5;
PositivePoint c = a + b;
std::cout << "Hello World!"<< std::endl;
std::cout << "c.X: " << c.mX << std::endl;
std::cout << "c.Y: " << c.mY << std::endl;
// your code goes here
return 0;
}