gpt4 book ai didi

C++ 我应该重载运算符吗?

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

<分区>

在我的一项作业之前和作业中,我从未使用过运算符重载,它说:

“仅在适当的情况下使用多态性。一般规则是,如果内置运算符匹配成员函数的目的,那么它应该被重载。”

我已经设法使这两个版本都能正常工作,而且我认为 ApplyFilter 的第二个版本更好。但是我使用运算符重载是否会使代码更难阅读?

非重载

int TheFilter::ApplyFilter(TheData& dataIn, TheData& dataOut) {
// other stuff here.
for (int i = 0; i < dataOut.length(); i++) {
dataOut.set_values(i, 0);
for (int j = 0; j < length(); j++) {
dataOut.set_values(i, ( dataOut.get_values(i)
+ (dataIn.get_values(i+j) * get_values(j)) ));
}
}
}

重载

int TheFilter::ApplyFilter(const TheData& dataIn, TheData& dataOut) {
// other stuff here
for (int i = 0; i < dataOut.length(); i++) {
dataOut[i] = 0;
for (int j = 0; j < length(); j++) {
dataOut[i] += dataIn[i+j] * values[j];
}
}
return OK;
}

编辑 - 我用于重载版本的数据类!

class TheData {
public:
int length()
double& operator[] (int index);
const double& operator[] (int index) const;
void print();
void resize(int);

private:
std::vector<double> values;
bool valid;
};

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