未找到采用类型为"B"的右操作数的运算符(或没有可接受的转换)
No operator found which takes a right-hand operand of type 'B' (or there is no acceptable conversion)
我有以下一段代码。我试图打印两个对象的和int,但编译器给了我以下错误:
binary '<<' : No operator found which takes a right-hand operand of type 'B' (or there is no acceptable conversion)
我真的不明白这个错误是什么意思。为什么说运算符<<需要"B"型。不是有两个整数的和吗?#include <iostream>
using namespace std;
class A
{
protected:
int x;
public:
A(int i) :x(i) {}
int get_x() {
return x;
}
};
class B : public A
{
public:
B(int i) :A(i) {}
B operator+(const B& b) const {
return x + b.x;
}
};
int main()
{
const B a(22), b(-12);
cout << a + b;
system("Pause");
}
重载<<接线员:
std::ostream& operator<<(std::ostream& out, const B& b)
{
return out << b.x;
}
a + b
表达式正在使用您的自定义操作符-所以它就像您写的(模块一致性-我只是想了解正在发生的事情):
B c = a + b;
cout << c;
这不起作用,因为编译器找不到合适的<<
操作符,B
作为正确的操作数-正如错误信息所说。不妨问问你自己,你希望它用它来做什么。
如果您想在结果中打印x
的值,也许您想:
cout << (a + b).get_x();
将operator <<
定义添加到B
类。就像
class B : public A {
public: B(int i) : A(i) {}
B operator +(const B & b) const { return x + b.x; }
friend std::ostream & operator <<(std::ostream & out, const B & obj) {
out << obj.x;
return out;
}
};
可以这样做:
#include<iostream>
using namespace std;
class A
{
protected: int x;
public: A(int i) :x(i) {}
int get_x() { return x; }
};
class B : public A
{
public: B(int i) :A(i) {}
B operator+(const B& b) const { return x + b.x; }
};
ostream & operator << (ostream &object,B &data)
{
object << data.get_x();
return object;
}
int main()
{
const B a(22), b(-12);
cout << (a + b);
system("Pause");
}
相关文章:
- 有没有一种方法可以通过"typedef"为重新定义的基本类型定义特征和强制转换运算符
- 构造函数和转换运算符之间的重载解析
- 分配给转换运算符失败-C++
- 转换运算符不适用于sleep_until
- 尝试使用算术运算符阻止隐式转换
- 错误 C2679:二进制"<<":未找到采用类型 'std::string_view' 的右侧操作数的运算符(或者没有可接受的转换)
- 是否可以将带有字符串化运算符的宏转换为 constexpr?
- C2678 二进制 '==':未找到采用 'Card' 类型左操作数的运算符(或者没有可接受的转换)
- 继承模板化转换运算符
- 将 OR 逻辑运算符从 C++ 转换为 Fortran
- 模板转换运算符在 clang 6 和 clang 7 之间的区别
- 如何在C++中正确重载运算符转换字符*?
- 将私有结构哈希器运算符转换为静态
- 混合类型的Boost运算符-转换和私有成员
- 如何将 c++ 运算符转换为 Java
- 运算符转换,GCC 和 clang:哪个编译器是正确的
- 将 istream 运算符>>转换为 istream getline
- 在C++中,将任意在位运算符转换为一元运算符
- 将运算符转换为 std::复杂<double>
- 为什么按位否定运算符"~"转换为 int?(从"int"转换为"无符号字符"可能会改变其值)