【问题标题】:C++ Should I overload operators? [closed]C++ 我应该重载运算符吗? [关闭]
【发布时间】:2014-02-05 18:29:11
【问题描述】:

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

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

我已经设法让两个版本都能正常工作,我认为 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;
}

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

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;
};

【问题讨论】:

标签: c++ operator-overloading overloading


【解决方案1】:

重载版本更加干净和直观。非重载更冗长。对于这些东西,我认为真的没有“正确的方法”。不过,我会在 C++ 程序中执行重载版本。

【讨论】:

    猜你喜欢
    • 2010-12-11
    • 1970-01-01
    • 2015-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多