向量< double>的*,+,-'运算符重载.班级 [英] overloading *, +, -'operators for vector<double> class
问题描述
我正在编写Line类来制作数值方法,并且我想要这些运算符(*,+,-) 使我的代码更具可读性并更易于理解.
I'm writing a Line class to make numerical methods and I want these operators (*, +, -) to make my code more readable and easier to understand.
#include <vector>
using namespace std;
typedef vector<double> Vector;
class Line : public Vector
{
public:
Line();
~Line();
Line operator+(Line);
Line operator-(Line);
Line operator*(double);
};
Line Line::operator*(double alfa)
{
Line temp;
int n = size();
temp.resize(n);
for (int i = 0; i < n; i++)
{
temp.at(i) = this->at(i)*alfa;
}
return temp;
}
Line Line::operator+(Line line)
{
int n = size();
Line temp;
temp.resize(n);
for (int i = 0; i < n; i++)
{
temp.at(i) = this->at(i) + line[i];
}
return temp;
}
Line Line::operator-(Line line)
{
int n = size();
Line temp;
temp.resize(n);
for (int i = 0; i < n; i++)
{
temp.at(i) = this->at(i) - line[i];
}
return temp;
}
int main()
{
return 0;
}
是否可以从Vector类中重载此类运算符?我应该只制作函数(或方法)而不是运算符吗?还有其他建议吗?
Is it possible to overload such operators from Vector class? should I just make functions (or methods) instead of operators? any other suggestions?
ps1:我正在使用Visual Studio 11作为编译器.
ps1: I'm using Visual Studio 11 as compiler.
ps2:我尚未将其作为"win32项目"启动,而是控制台应用程序.
ps2: I have not started the project as 'win32 project', it's console application.
我遇到以下错误:
Error 1 error LNK2019: unresolved external symbol "public: __thiscall Line::Line(void)" (??0Line@@QAE@XZ) referenced in function "public: class Line __thiscall Line::operator*(double)" (??DLine@@QAE?AV0@N@Z) C:\Users\Lucas\Documents\Visual Studio 11\Projects\test\test\test.obj test
Error 2 error LNK2019: unresolved external symbol "public: __thiscall Line::~Line(void)" (??1Line@@QAE@XZ) referenced in function "public: class Line __thiscall Line::operator*(double)" (??DLine@@QAE?AV0@N@Z) C:\Users\Lucas\Documents\Visual Studio 11\Projects\test\test\test.obj test
推荐答案
您必须在全局范围内重载运算符:
You have to overload the operators at global scope:
vector<double> operator*(const vector<double>& v, double alfa)
{
...
}
vector<double> operator+(const vector<double>& v1, const vector<double>& v2)
{
...
}
vector<double> operator-(const vector<double>& v1, const vector<double>& v2)
{
...
}
对于链接器错误,似乎您没有实现Line构造函数和析构函数.
As for the linker errors, it just looks like you didn't implement the Line constructor and destructor.
这篇关于向量< double>的*,+,-'运算符重载.班级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!