无法使用友元函数为模板类正确编写 operator+ 代码。 只有一个问题:为什么编译错误?以及如何解决?
template <typename T>
class A {
T a;
public:
A(T a) : a(a) {
}
template<typename K>
friend A<K> operator +(const A<K> &a, const A<K> &b) {
return A<K>(a.a + b.a);
}
};
int main(int argc, const char **argv) {
A<int> a(1);
A<int> b(2);
a + b; // no compilation error
(A<int>)1 + a; // no compilation error
1 + a; // compilation error
return 0;
}
g++ 输出:
07-04.cpp: In function ‘int main(int, const char**)’:
07-04.cpp:20:7: error: no match for ‘operator+’ (operand types are ‘int’ and ‘A<int>’)
1 + a; // compilation error
^
07-04.cpp:10:17: note: candidate: template<class K> A<K> operator+(const A<K>&, const A<K>&)
friend A<K> operator +(const A<K> &a, const A<K> &b) {
^
07-04.cpp:10:17: note: template argument deduction/substitution failed:
07-04.cpp:20:9: note: mismatched types ‘const A<K>’ and ‘int’
1 + a; // compilation error
^
最佳答案
operator+
方法应该使用 A<T>
,而不是它自己的模板。
friend A<T> operator +(const A<T> &a, const A<T> &b) {
return A<T>(a.a + b.a);
}
关于c++ - 为模板类编写二元加法运算符。编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49783997/