未找到采用类型为"B"的右操作数的运算符(或没有可接受的转换)

No operator found which takes a right-hand operand of type 'B' (or there is no acceptable conversion)

本文关键字:运算符 转换 可接受 操作数 类型      更新时间:2023-10-16

我有以下一段代码。我试图打印两个对象的和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");
}