我正在學習C 的OOP,我寫了這段代碼來學習更多關于繼承的知識。
#include<bit/stdc .h>/span>
using namespace std;
class Employee {
public:
字串名稱。
int age;
int weight;
Employee(string N, int a, int w) {
name = N;
年齡 = a;
重量 = w;
}
};
// this means the class developer inherits from employee.
class Developer: Employee {
public:
string favproglang; //this is only with respect to developer employee.
//現在我們必須要宣告建構式。
開發人員(string name, int age, int weight, string fpl)
//這將確保不需要重新分配名稱、年齡和重量,它將由父類分配。
:Employee(name, age, weight){
favproglang = fpl;
}
void print_name() {
cout << name << " is the name"/span> << endl;
}
};
int main() {
開發者d = 開發者("Hirak"/span>, 45, 56, "C "/span>) 。
cout << d.favproglang << endl;
d.print_name()。
cout << d.name << endl; //this line gives error。
return 0;
}
在這里,開發人員類繼承于雇員類,但是當我試圖從主函式中列印開發人員的名字時 cout << d.name << endl;我得到了這個錯誤 'std::string Employee::name' 在這個背景關系中無法訪問。
我不明白為什么我會得到這個錯誤?我已經在父類中把所有的屬性都宣告為公共屬性。當我試圖從開發者類本身訪問name時,這個錯誤并不存在,你可以在函式print_help()中看到。此外,我也可以從主函式中列印d.favproglang,但為什么不是d.name?任何幫助都將被高度贊賞。謝謝你。
uj5u.com熱心網友回復:
這是因為繼承的默認訪問控制是 "私有"。
如果你改變這一點:
//這意味著該類開發人員繼承自employee。
class Developer: Employee {
對這個:
// this means the class developer inherits from employee.
class Developer。public Employee {}。
默認情況下,類的繼承是 "私有 "繼承,結構的繼承是 "公共 "繼承。私有繼承意味著基類的公共和受保護成員將被子類當作私有成員對待。
你可以通過在基類名稱前明確寫上public、private或protected來覆寫這一默認行為。
搜索 "C 基類成員訪問控制 "以了解更多資訊。
uj5u.com熱心網友回復:
對此有2種解決方案(直接的)。
解決方案1
解決方案1 將Employee和Developer類的 解決方案2 在派生串列中添加關鍵字
標籤:class關鍵字替換為struct關鍵字。請注意,即使你用struct替換Developer的class關鍵字,并保留Employee的class關鍵字,這也會有效。
public,如下一行所示:class Developer:public Employee
