gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 04:43:50 27 4
gpt4 key购买 nike

我正在编写一些 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com