为模板类编写二进制加法运算符. 编译错误
Writing binary addition operator for template class. Compilation error
无法使用友元函数为模板类正确编码运算符+。只有一个问题:为什么编译错误?以及如何解决它?
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++中的条件运算符 ( ? : ) 可以编译时吗?
- 编译"运算符删除"时C++编译器如何工作?
- 为什么 std::make_shared 无法编译带有已删除运算符 new 的类型?
- 使用 MINGW gcc 编译时,不会为 std::string 调用重载的新运算符
- 编译我的 3 个文件时,我收到错误,说"运算符="不匹配
- 使用堆栈编译错误的 C++ 反向行没有运算符匹配操作数
- 代码块编译错误与运算符<<不匹配
- ostream 运算符的编译时重载
- 编译Qt项目给出了对运算符delete(void*,unsigned int)的未定义引用
- <<运算符覆盖使用 g++ 而不是窗口编译
- 为什么有条件编译运算符模板会更改另一个运算符的可用性?
- 在 sizeof 运算符上强制编译时错误
- 如何在C++编译时检查运算符的特定重载是否存在
- 为模板类编写二进制加法运算符. 编译错误
- 重载运算符编译错误?
- 三元运算符编译
- C++模板运算符编译错误
- C++中重载运算符编译但崩溃
- C++ GMP 库 ostream 运算符<<编译但不链接?
- 重载运算符+编译错误没有匹配函数调用...