[英]Why object of derived class d cannot call the protected member function of the class base?
這里派生的 class d
的 object 不能調用 ZA2F2ED4F8EBC2CBB4C21A29DC 基的受保護成員 function。
#include <iostream>
using namespace std;
class base
{
protected:
int i,j;
void setij(int a,int b)
{
i=a;
j=b;
}
void showij()
{
cout<<i<<" "<<j<<endl;
}
};
class derived : protected base
{
int k;
public:
void show()
{
base b;
b.setij(10,20);
b.showij();
}
};
int main()
{
base b;
derived d;
d.setij(3,4);
d.showij();
d.show();
return 0;
}
我預計 output 是10 20
,但編譯器顯示錯誤。
您使用了protected
的 inheritance。 問題不在於派生無法訪問基的受保護方法,而問題是您無法從derived
外部訪問基方法。
如果您不知道受保護的 inheritance 是什么意思,您可以在這里閱讀私有、公共和受保護 inheritance 之間的區別
我懷疑你想在這里使用protected
的 inheritance(你為什么要這樣做?)。 將其更改為public
inheritance 並且您的代碼應該沒問題:
class derived : public base ...
PS:錯誤消息應該告訴您實際問題是什么(盡管以一種神秘的方式)。 請下次將其包含在問題中。 如果你不能理解它,可能其他人會。
這段代碼有很多錯誤。 即使將protected
derived
的class的inheritance改為public
,仍然存在以下問題:
在 class derived
,語句b.setij(10,20);
和b.showij();
仍然會產生編譯器錯誤。 請參閱為什么派生的 class 不能在此代碼中調用受保護的成員 function? 一個很好的解釋。 簡短的解釋:一個方法只能在最初調用它的 object 上的基礎 class 中調用受保護的方法。
Function main
將無法調用d.setij(3,4);
或d.showij();
因為這些是 class base
中的受保護方法。
這應該運行:
#include <iostream>
using namespace std;
class base
{
protected:
int i,j;
void setij(int a,int b)
{
i=a;
j=b;
}
void showij()
{
cout<<i<<" "<<j<<endl;
}
};
class derived : public base
{
int k;
public:
void show()
{
this->setij(10,20);
this->showij();
}
};
int main()
{
derived d;
d.show();
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.