C++ 在c+;中以私有继承类的形式返回字符串+;

C++ 在c+;中以私有继承类的形式返回字符串+;,c++,oop,inheritance,C++,Oop,Inheritance,我有一个类,它私下继承了std::string。我想要一个成员函数,它返回作为基类的字符串。我该怎么做 class NewClass() : private std::string { ... public: std::string GetString() const; ... }; std::string NewClass::GetString() const { ??? } 像这样: #include <string> class NewClas

我有一个类,它私下继承了
std::string
。我想要一个成员函数,它返回作为基类的
字符串。我该怎么做

class NewClass() : private std::string
{
    ...
public:
    std::string GetString() const;
    ...
};

std::string NewClass::GetString() const
{
  ???
}
像这样:

#include <string>

class NewClass
    : private std::string
{
public:
    const std::string& GetString() const{
        return *this;
    }
};

int main() {
    NewClass c;
    const std::string& the_string = c.GetString();
    return 0;
}
#包括
类NewClass
:private std::string
{
公众:
常量std::string&GetString()常量{
归还*这个;
}
};
int main(){
新c类;
const std::string&the_string=c.GetString();
返回0;
}

您最好保留一个
std::string
作为
NewClass
的私有成员。因此,您将其声明为:

class NewClass
{
private:
     std::string str;
...
public:
    std::string GetString() const;
};
...
std::string NewClass::GetString() const
{
    return str;
}
但是,如果您确实需要从
std::string
继承,您可以这样做

std::string NewClass::GetString() const
{
    return *this;
};
但请注意,这将删除派生类的任何部分。最好是这样做:

const std::string& NewClass::GetString() const
{
    return *this;
};

它将返回对继承自的std::string
NewClass
的引用。

谢谢!我知道遏制可能更好,但我正好有这个问题。谢谢!这里的两个答案基本相同。如果您希望能够返回一个
字符串
,为什么不直接继承
public
ly,这样您就不需要这个函数了?