c++ - 二元运算符 + , = 用 const 重载

标签 c++ operator-overloading

我正在学习 C++ 概念,非常感谢任何解释帮助。为什么语句 4 不能编译,但语句 1 可以编译。

class X {
    public:
            X& operator= (const X& rhs);
            const X& operator+ (const X& rhs) const;
            const X& operator+ (int m);
    private:
            int n;
};

int main() {
        X a, b, c;
        a = a + 5 + c; //statement 1 - No compiler errors
        a = b + 5; //statement 2
        a = a = b + c; //statement 3
        a = b + c + 5; //statement 4 /*compiler Error thrown -
passing 'const X' as 'this' argument of 'const X& X::operator+(int)' discards qualifiers
 [-fpermissive]*/
        (c = a + a) = b + c; //statement 5
}

根据我的理解(基于:+ & = 都是右结合的)以上 5 个语句被解读为 -

//statement 1
a.operator=(a.operator+(5.operator+(c)));

-->我相信这应该引发错误,因为没有定义的构造函数支持此

//statement 2
a.operator=(b.operator+(5));

//statement 3 
a.operator=(a.operator=(b.operator+(c)));

//statement 4
a.operator=(b.operator+(c.operator+(5)));

//statement 5
(c.operator=(a.operator+(a)))=(b.operator+(c)); then
lhs_result.operator=(rhs_result);

我是否正确解读了上面的第 5 条陈述?

最佳答案

如果您希望编译语句 4,则声明运算符如下

const X& operator+ (int m) const;

问题在于这个语句

a = b + c + 5;

b + c 是一个 const 对象。请参阅相应的运算符声明

        const X& operator+ (const X& rhs) const;

你不可以为const对象调用非const成员函数。

考虑加法运算符 + 从左到右分组。 来自 C++ 标准(5.7 加法运算符)

1 The additive operators + and - group left-to-right.

至于语句5

(c = a + a) = b + c; //statement 5

那么它具有未定义的行为,因为赋值运算符的操作数的计算没有排序。 因此,要么首先计算表达式 (c = a + a),然后计算表达式 b + c。 或者首先计算表达式 b + c,然后才计算表达式 (c = a + a)

关于c++ - 二元运算符 + , = 用 const 重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27821297/

相关文章:

c++ - 对 map<> 使用自己的 Comparator operator()。如果找不到 KEY 则给出错误

c++ - 重载运算符 >>()

C++ Typedef 和运算符重载

c++ - 使用 StyleSheet 悬停时 qt 加宽 QScrollBar

c++ - 在 std::string::end() 和 std::string::capacity() 之间使用缓冲区

c++ - 将指向 C++ 成员函数的指针传递给 C API 库

c++运算符<<重载不打印出 vector

c++ 在单独的 .cpp 和 .h 文件中创建一个类

c++ - 防止在C++中显示小数点前的零

c++ - 为类重载 C++ 插入运算符 (<<)