2014-01-06 113 views
2

我在處理這個錯誤時遇到了一些麻煩。所以我有一個Person類和一個Student子類。C++繼承獲取錯誤

Person類具有下面的構造:

Person(const string &name) 
     { this->name = name; 
     } 

學生類具有以下構造:

Student::Student(const string &name, int regNo) 
{ this->name = name; 
    this->regNo = regNo; 
} 

當我嘗試雖然編譯Student類,我得到這個錯誤的構造函數:

In constructor 'Student::Student(const string&, int)':

error: no matching function for call to 'Person::Person()'

我是新來的C++,所以我不知道爲什麼我得到這個呃但是這顯然與人的繼承有關。

回答

11

您正試圖呼叫Person的默認構造函數,但它沒有一個。在任何情況下,它看起來像你想要做的就是調用其單個參數的構造函數是什麼:

Student::Student(const string& name, int regNo) : Person(name), regNo(regNo) 
{ 
} 

同樣,在Person的consructor使用構造函數初始化列表:

Person(const string& name) : name(name) {} 

這樣,你初始化您的數據成員到所需的值,而不是默認初始化它們,然後分配他們的新值。

6

你需要從基類委託給正確的構造函數是這樣的:

Student::Student(const string &name, int regNo) 
    : Person(name) 
{ 
    this->regNo = regNo; 
} 

注意,這裏使用初始化列表,這樣你就可以使用更地道

Student::Student(const string &name, int regNo) 
    : Person(name), regNo(regNo) 
{ 
} 

,爲Person ctor:

Person(const string &name) 
    : name(name) 
{ 
} 

初始化程序列表用於初始化基類和成員變量,你沒有明確地放在那裏的所有東西都是默認構造的(並且在你的代碼中,它稍後分配在ctor的主體中)。由於Person不是默認可構造的,因此您的必須在初始化程序列表中初始化它。