问题描述
我正在使用 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 A
和 struct B
添加任何代码的情况下解决问题?
解决方法
您需要创建以 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
作为输入和输出。
您还可以重载 operator+
的 C class
以允许 c1 + c2
代码返回 C
对象而不是 B
对象(正如目前由于 operator+
类中定义的 B
所做的那样)。通过这种方式,您可以获得一个 C
对象作为 c1+c2
的结果,该对象可以使用类 operator=
中定义的 C
进行赋值。
例如,将此函数添加到 C class
中,如下所示:
C& operator+(const C& other){
// for example add the two operands' characters
this->a += other.a;
return *this;
}
注意你的选择背后的想法,因为它可能会编译但不会做你想做的事。
重载 +
或 =
可能取决于您希望对代码执行的操作以及希望从操作 c1+c2
中获取的类型。