![](/img/trans.png)
[英]Are Private members of base class always inherited in derived class in C++?
[英]Return a string as private inherited class in c++
我有一个私下继承std::string
。 我想要一个成员函数,该函数返回作为基类的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;
}
您最好保留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;
};
这将返回对NewClass
继承的std :: string的引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.