重载*,+,-'vector <double>类的运算符

Luc*_*uza 4 c++ class operator-overloading stdvector

我正在编写Line类来制作数值方法,并且希望这些运算符(*,+,-)使我的代码更易读和更易于理解。

        #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;
        }
Run Code Online (Sandbox Code Playgroud)

是否可以从Vector类重载此类运算符?我应该只制作函数(或方法)而不是运算符吗?还有其他建议吗?

ps1:我使用Visual Studio 11作为编译器。

ps2:我尚未将项目启动为“ win32项目”,它是控制台应用程序。

我收到以下错误:

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
Run Code Online (Sandbox Code Playgroud)

use*_*015 5

您必须在全局范围内重载运算符:

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)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

至于链接器错误,似乎您没有实现Line构造函数和析构函数。