如何在C++上的多个继承上下文上使用特定基类中的运算符



我正在编写一些C++代码,但我无法在 g++ 上编译以下代码。它只说 std::string 没有一个名为"operator=="的方法。我知道这不是事实,但也许有一些多重继承限制或我还不知道的问题。

代码:

#include<string>
struct Object{
constexpr Object() noexcept = default;
virtual ~Object() noexcept = default;
virtual bool operator==( const Object& other) const noexcept = 0;
};

class String : public Object, public std::string{
virtual ~String() noexcept = default;
String() noexcept = default;
virtual bool operator==( const Object& other) const noexcept{
auto ptr =  dynamic_cast<const String*>(&other);
return ptr != nullptr &&
this->std::string::operator==(*ptr);    // here is the error
}
};
int main(){}

错误:

$ g++ -std=c++11 test.cpp -o test.run

test.cpp:在成员函数'Virtual bool String::operator==(const Object&( const':
test.cpp:23:31:error: 'class std::__cxx11:::basic_string'没有名为'operator=='的成员;你的意思是'operator='吗? this->std::string::operator==(*ptr(;

它没有运算符作为成员,它是一个全局运算符。

((std::string&)*this) == (*ptr);

请参阅文档中的非成员函数部分:https://en.cppreference.com/w/cpp/string/basic_string

最新更新