我应该以哪种方式访问此父方法和父变量?
class Base
{
public:
std::string mWords;
Base() { mWords = "blahblahblah" }
};
class Foundation
{
public:
Write( std::string text )
{
std::cout << text;
}
};
class Child : public Base, public Foundation
{
DoSomething()
{
this->Write( this->mWords );
// or
Foundation::Write( Base::mWords );
}
};
谢谢。
编辑:如果有歧义怎么办?
最佳答案
仅在存在歧义或其他一些名称查找问题(例如名称隐藏,模板基类等)时,才有必要在代码中使用两种语法(this->...
和限定名称)。
如果没有歧义或其他问题,则不需要任何这些语法。您需要的只是一个简单的无限定名称,例如您的示例中的Write
。只是Write
,而不是this->Write
和Foundation::Write
。 mWords
也是如此。
IE。在您的特定示例中,简单的Write( mWords )
可以正常工作。
为了说明上述内容,如果您的DoSomething
方法具有mWords
参数,例如
DoSomething(int mWords) {
...
那么此本地
mWords
参数将隐藏继承的类成员mWords
,您必须使用其中一个DoSomething(int mWords) {
Write(this->mWords);
}
或者
DoSomething(int mWords) {
Write(Foundation::mWords);
}
正确表达您的意图,即突破藏身之路。
如果您的
Child
类也有自己的mWords
成员,例如class Child : public Base, public Foundation
{
int mWords
...
那么此名称将隐藏继承的
mWords
。在这种情况下,this->mWords
方法不会帮助您取消隐藏专有名称,并且您必须使用限定名称来解决问题。DoSomething(int mWords) {
Write(Foundation::mWords);
}
如果您的两个基类都有一个
mWords
成员,例如class Base {
public:
std::string mWords;
...
};
class Foundation {
public:
int mWords;
...
然后在
Child::DoSomething
中,mWords
名称将是不明确的,而您必须这样做DoSomething(int mWords) {
Write(Foundation::mWords);
}
解决歧义。
但是,再次,在您的特定示例中,没有歧义,也没有名称隐藏所有这些都是完全没有必要的。
关于C++:访问父方法和变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4523545/