我正在寫一個Line類來創建數值方法,我希望這些運算符(*,+, - ) 能使我的代碼更易讀易懂。重載*,+,-'operators for vector <double>類
#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類中重載這些運算符?我應該只是做功能(或方法),而不是操作員?任何其他建議?
ps1:我使用Visual Studio 11作爲編譯器。
ps2:我還沒有啓動項目作爲'win32項目',它是控制檯應用程序。
我歌廳以下錯誤:
Error 1 error LNK2019: unresolved external symbol "public: __thiscall Line::Line(void)" ([email protected]@[email protected]) referenced in function "public: class Line __thiscall Line::operator*(double)" ([email protected]@[email protected]@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)" ([email protected]@[email protected]) referenced in function "public: class Line __thiscall Line::operator*(double)" ([email protected]@[email protected]@Z) C:\Users\Lucas\Documents\Visual Studio 11\Projects\test\test\test.obj test
繼承自'std :: vector'是一個非常糟糕的主意。另外,你從來沒有定義你的ctor/dtor。 – chris
我應該只是做功能,或者你有另一個想法? –
標準容器的組成通常會更好。 – chris