2016-07-05 117 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) 
{ 
// ... 
} 

将是一种可能性。您尚未解释基类构造函数应该接收的确切参数;适当调整。

相关问题