不能调用重载运算符
cannot have an overloaded operator called
>我尝试从派生类调用一个运算符==
但是如果我使用基类指针,它不起作用,尽管对象是作为派生类创建的
class A
{
public:
bool operator==(const A & other)
{
cout << "this should never been called" << endl;
return this==&other;
}
};
class B : public A
{
public:
bool operator==(const A & other)
{
cout << "this should be called instead" << endl;
return this==&other;
}
};
void process(A _b1,A _b2)
{
if(_b1==_b2)
{
cout << "here" << endl;
}
}
int main()
{
B b1;
B b2;
process(b1,b2);
}
虽然运算符重载具有相同的签名,但我不明白
请帮帮我
感谢
首先,类 A 中的 bool 运算符==() 应该virtual
。喜欢:
class A
{
public:
virtual bool operator==(const A& other) { ... }
};
这意味着,即使你提到A类,它也可以被视为B类,如果这是它的真实情况。
其次,将 B 实例复制到 A 实例。这是您不想要的转换。相反,您应该"通过引用"传递它们。喜欢这个:
void process(A& _b1,A& _b2)
{
...
}
这样,当它们被实际处理时,它们仍然引用原始对象,这些对象属于 B 类。
问题是void process(A _b1,A _b2)
,它会对 A 类中的 B 类进行隐式转换/向上转换,所以它被称为 A 运算符==,你应该改变你的代码以支持多态性:
class A
{
public:
virtual bool operator==(const A & other)
{
cout << "this should never been called" << endl;
return this==&other;
}
};
class B : public A
{
public:
virtual bool operator==(const A & other)
{
cout << "this should be called instead" << endl;
return this==&other;
}
};
void process(A& _b1,A& _b2)
{
if(_b1==_b2)
{
cout << "here" << endl;
}
}
int main()
{
B b1;
B b2;
process(b1,b2);
}
再见安杰洛
相关文章:
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- <T> 通过模板化运算符重载将 std::complex 乘以双倍
- C++20概念:需要运算符重载
- 使用赋值运算符重载从类中返回jobject
- 在运算符重载定义中使用成员函数(const错误)
- 字节到位运算符重载C++
- 为什么在运算符重载时需要参考?
- 类中 c++ 的运算符 + 重载
- 算术复合运算符重载为非成员
- 运算符重载 (+),用于添加两个具有 C++ 的数组
- 交换运算符 + 重载会导致无限递归
- 如何理解新的运算符重载?
- 向量保持复数的运算符重载
- 如何创建运算符重载?
- 链接列表运算符重载没有打印出我想要的内容
- C++:需要帮助了解运算符重载错误
- 使用模板化运算符重载 XOR 运算符失败
- 如何确保接受的C++模板类型使运算符重载?
- 运算符重载使用运算符+添加类模板