'How to use an operator from a specific base class on multiple inheritance context on C++
I'm writing some C++ codes, and I can't compile the following code on g++. It only says that std::string hasn't a method named "operator==". I know it's not truth, but perhaps there is some multiple inheritance restrictions or problems I don't know yet.
The code:
#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(){}
The error:
$ g++ -std=c++11 test.cpp -o test.run
test.cpp: In member function ‘virtual bool String::operator==(const Object&) const’:
test.cpp:23:31: error: ‘class std::__cxx11::basic_string’ has no member named ‘operator==’; did you mean ‘operator=’? this->std::string::operator==(*ptr);
Solution 1:[1]
It doesn't have the operator as a member, it is a global operator.
((std::string&)*this) == (*ptr);
See non-member functions section in the docs: https://en.cppreference.com/w/cpp/string/basic_string
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | robthebloke |