gpt4 book ai didi

c++ - 为 vector 类重载 *, +, -' 运算符

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:24:13 25 4
gpt4 key购买 nike

我正在编写一个 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;
}

是否可以从 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

最佳答案

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

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 构造函数和析构函数。

关于c++ - 为 vector<double> 类重载 *, +, -' 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14420209/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com