c++ - 如何在 C++ 的多重继承上下文中使用来自特定基类的运算符

标签 c++ operators virtual multiple-inheritance

我正在编写一些 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: 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);

最佳答案

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

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

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

关于c++ - 如何在 C++ 的多重继承上下文中使用来自特定基类的运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58003963/

相关文章:

c++ - 在 STL 优先级队列 C++ 中实现 decreaseKey

c++ - 从 int64 和 uint64 C++ 转换时的精度损失?

Haskell 缺点运算符 (:)

java - 在java中使加号成为一个字符串

c++ - 旋转球形点系统

c++ - 如何在同一系统中为不同的用户帐户注册相同的 COM dll

C++ 重载 : operator+ for adding Matrices by element

c++ - 虚函数——指针在哪里?

.net - 为什么我可以密封一个实现接口(interface)的类,但不能密封一个成员?

c++ - 虚拟类: are pointers the clean way to go?的 vector