当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - Private inheritance got "an inaccessible base" error

问题描述:

Here is MY_STRING class implementation. Since I wish only some of specified interfaces visible I use private inheritance instead of public.

class MY_STRING : private std::string

{

public:

MY_STRING() : std::string() {}

MY_STRING(const char* s) : std::string(s) {}

using std::string::operator +=;

};

int main()

{

MY_STRING s = "1", x = "2";

s += x;

}

But I got a compilation error: 'std::basic_string' is an inaccessible base of 'MY_STRING'.

Even though I had a ugly solution as follows

const MY_STRING& operator += (const MY_STRING& s) { static_cast<std::string*>

(this)->operator+=(*static_cast<const std::string*>(&s)); return *this; }

I still wonder why the error arises and if there is more elegant solution.

网友答案:

You can only use std::string::operator+= from within member functions of MY_STRING. Outsiders cannot use it. You can't "promote" it with using or anything.

That's what private inheritance means. Private inheritance is, in effect, the same as having a private member variable, just that syntax is different within the member functions of MY_STRING.

To fix this you will either have to not use private inheritance, or write a forwarding function for those that you want to publish.

Also, your forwarding function seems unnecessarily complicated, try:

MY_STRING &operator+= (MY_STRING const &s)
    { std::string::operator+=(s); return *this; }

You don't want to return a const reference when called on a non-const object (and += doesn't make sense for a const object).

分享给朋友:
您可能感兴趣的文章:
随机阅读: