2016-07-05 122 views
-2

我想定義派生類的構造函數並使用我定義的基類構造函數。我已經評論了派生類的構造函數代碼。如何使用基類構造函數

#include "stdafx.h" 
#include "iostream" 
#include "stdio.h" 
#include "string" 

using namespace std; 

class person{ 
    private: 
     string name; 
     int age; 

    public : 
     person(int,string); //constructor 
}; 

class student : public person{ //derived class 
    private : 
     string teacher; 
    public : 
     student(string); 
}; 

person :: person(int newage,string newname){ 

    age = newage; 
    name = newname; 
    cout <<age << name; 
} 
/* How do I define the derived class constructor , so that by default 
    it calls base class person(int,string) constructor. 
student :: student(string newteacher){ 
    teacher = newteacher; 
    cout<<teacher; 

} 
*/ 
int _tmain(int argc, _TCHAR* argv[]) 
{ 
    person p(20,"alex"); 
    student("bob"); 

    return 0; 
} 

中添加更多細節:

我想定義我的派生類的構造函數的方式,我可以打電話給我的派生類constructor.Right內基類的構造函數,如果現在我去掉我的派生類的構造函數我得到以下錯誤「沒有默認構造函數存在類人」。是否有可能做這樣的事情:

student object("name",10,"teacher_name") 

姓名,年齡應使用基類的構造函數初始化和TEACHER_NAME應使用派生類的構造函數初始化。我是C++的新手,所以如果這樣的事情是不可能的,請告訴我。

回答

0
student :: student(string newteacher) : person(0, newteacher) 
{ 
// ... 
} 

將是一種可能性。您尚未解釋基類構造函數應該接收的確切參數;適當調整。

相關問題