【问题标题】:C++ inheritance and assignment operatorC++ 继承和赋值运算符
【发布时间】:2021-06-07 07:39:59
【问题描述】:

我正在使用 CRTP 来实现 C++ 功能。

现在我遇到了这样的情况。

template<typename T>
struct A {
    char a;

    T operator+(const T& other){
        T t;
        t.a = a + other.a;
        return t;
    }
};

struct B : A<B>{

};

struct C : B {
    C& operator=(const C& other){
        a = other.a;
        return *this;
    }
};

int main() {
    C c1,c2,c3;
    c3 = c1 + c2;
    return 0;
}

这段代码编译不上no viable overloaded=

如何在不向struct Astruct B 添加任何代码的情况下解决此问题?

【问题讨论】:

    标签: c++ inheritance operator-overloading assignment-operator crtp


    【解决方案1】:

    您需要创建以B 为参考的赋值运算符:

    struct C : B {
        C& operator=(const C& other){
            return *this = static_cast<const B&>(other);
        }
    
        C& operator=(const B& other){
            a = other.a;
            return *this;
        }
    };
    

    简短的解释为什么你需要这个(我希望我没有错):

    + operator 返回一个B 引用,因为B 是模板参数,而不是C。所以忽略+ 会有一个分配C = B 这是不可能的。需要明确的是,您不需要第一个赋值运算符来运行您的代码。

    也许这也更清楚更好:

    struct C : B {
        B& operator=(const B& other){
            a = other.a;
            return *this;
        }
    };
    

    现在您的赋值运算符将B 作为输入和输出。

    【讨论】:

    • 你是对的,我会接受这个答案
    【解决方案2】:

    您还可以为C class 重载operator+ 以允许c1 + c2 代码返回C 对象而不是Bobject(由于@987654326,它目前确实如此@ 在B 类中定义)。通过这种方式,您可以获得一个 C 对象,作为 c1+c2 的结果,可以使用类 C 中定义的 operator= 进行分配。

    例如,将此函数添加到C class,如下所示:

    C& operator+(const C& other){
            // for example add the two operands' characters
            this->a += other.a;
            return *this;
        }
    

    请注意您选择背后的想法,因为它可能会编译但不会执行您希望它执行的操作。

    重载+= 可能取决于您希望对代码执行的操作以及您希望从操作c1+c2 获得的类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-15
      • 2012-02-28
      • 2015-02-09
      • 2021-08-28
      • 2018-11-24
      • 1970-01-01
      • 2011-08-12
      • 1970-01-01
      相关资源
      最近更新 更多