我读过 this ,但该讨论仅涉及比较以基类或派生类为参数的运算符。在我的例子中,我想为完全不同的参数(在本例中为 std::string)继承虚拟运算符,但我什至找不到关于这个主题的讨论。
所以在我的例子中,我有以下代码:
#include <string>
#include <iostream>
class Base {
public:
Base(std::string s) : str(s) {}
virtual bool operator==(const std::string& s) const { return s == str; };
protected:
std::string str;
};
class Derived : public Base {
public:
Derived(std::string s) : Base(s) {}
//bool operator==(const std::string& s) const override { return s == str; };
//bool operator==(const double& d) const { return d == doub; };
protected:
double doub;
};
int main() {
std::string foo = "foo";
Derived object(foo);
if (object == foo)
std::cout << "equal" << std::endl;
}
在这种情况下,字符串的运算符是正确派生的(代码正在编译)。但是,如果我想为类型 double 定义另一个运算符(取消注释第二条注释),则代码不会编译,因为编译器看不到基类中定义的字符串的运算符。取消注释第一个注释,即显式覆盖 base 的运算符再次起作用。
谁能解释这种行为?
最佳答案
假设你有
class Derived : public Base {
public:
Derived(std::string s) : Base(s) {}
bool operator==(const double& d) const { return d == doub; };
protected:
double doub;
};
这里的问题是您的 Derived::operator==
函数隐藏 Base::operator==
函数。
这可以通过将 Base
类中的 operator==
符号拉入 Derived
类来解决,使用
关键词:
class Derived : public Base {
public:
Derived(std::string s) : Base(s) {}
using Base::operator==; // Get the symbol from the Base class into the scope of the Derived class
bool operator==(const double& d) const { return d == doub; };
protected:
double doub;
};
关于c++ - 继承和覆盖虚拟赋值 == 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53502570/