[英]Why does this give me an error when using Inheritance
我目前正在學習 Inheritance。 下面的代碼工作得很好。
#include <iostream>
class Student {
protected:
double GPA = 3.12;
};
class Employee {
protected:
int Salary = 1500;
};
class TeachingAssistant: public Student, public Employee {
public:
void Print() {
std::cout << GPA << " " << Salary << "\n";
}
};
int main() {
TeachingAssistant TA;
TA.Print();
}
但是,下面的代碼不起作用。
#include <iostream>
class Student {
protected:
double GPA = 3.12;
};
class Employee: public Student {
protected:
int Salary = 1500;
};
class TeachingAssistant: public Student, public Employee {
public:
void Print() {
std::cout << GPA << " " << Salary << "\n";
}
};
int main() {
TeachingAssistant TA;
TA.Print();
}
我只在這兩個代碼片段之間更改了一件事,就是在 class Employee 旁邊添加了“public Student”。 我做錯了什么? 請使用簡單的文字/邏輯來解釋這一點。
可以通過兩種方式從 class TeachingAssistant
訪問現場GPA
:
TeachingAssistant -> Student
TeachingAssistant -> Employee -> Student
您必須指定您需要哪一個
例如:
std::cout << Employee::GPA << " " << Salary << "\n";
另一種解決方案是刪除 class Student
的另一個 inheritance :
class TeachingAssistant: public Employee {
public:
void Print() {
std::cout << GPA << " " << Salary << "\n";
}
};
您的情況如下:您有一個助教,他是 Student (1) 和 Employee (2) - 但是基於您的設計的 Employee也是 student 。 你最終會讓助教成為兩名學生和一名員工。 C++ 告訴您要我為哪個學生打印 GPA,因此ambiguous
。
第二個代碼片段中的設計完全錯誤。
TeachingAssistant 既是員工又是學生:是的。
員工是學生:不。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.