c++ - 如何覆盖||在 C++ 中

标签 c++ operator-overloading overriding overloading

<分区>

我如何重写 || 来计算一些东西?我试过这些,但它不起作用

主要是:

obj || 1;

在类里面:

ostream& MyClass::operator||(ostream & i)
{
    if (i > 0) 
    { 
        cout << i;
    }
    else 
    {

    } 
    return *this;
}

最佳答案

您错误地声明了类的operator||

您的 main 代码没有传入 ostream 对象,而是传入一个整数,因此 operator 需要接收一个整数作为输入,例如:

class MyClass
{
//...
public:
    MyClass& operator||(int i);
//...
};

MyClass& MyClass::operator||(int i)
{
    if (i > 0)
    {
        cout << i;
    }
    else
    {
        //...
    }
    return *this;
}

Live Demo

关于c++ - 如何覆盖||在 C++ 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50710287/

相关文章:

ios - Swift 3 - 覆盖 UINavigationController 的初始值设定项以设置 rootviewcontroller

python - 如何重写枚举构造函数?

c++ - const 参数 vs const 引用参数

c++ - 如何销毁 C++ 中的指针 vector ?

css - 如何覆盖 Material UI .MuiContainer-maxWidthLg?

c++ - 为什么 <iostream> operator<< 选择明显错误的重载?

c++ - 尝试使用 cout 打印 vector 中包含的对象列表,但排序错误

python - 通过嵌入式 Python 调用 C++ 代码

c++ - 使用 boost::shared_ptr 时有哪些潜在危险?

C++ 重载 operator= 用于不同的 rhs 类型,在构造时