如何使用基类构造函数

时间:2016-07-05 19:01:45

标签: c++ oop

我想为派生类定义一个构造函数,并使用我定义的基类构造函数。我已经评论了派生类的构造函数代码。

#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;
}

添加更多详情:

我想以某种方式定义我的派生类构造函数,我可以在派生类构造函数中调用基类构造函数。现在如果我取消注释我的派生类构造函数,我会得到以下错误&#34;没有默认构造函数存在对于班级人员。&#34;。是否可以做类似的事情:

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

name,age应该使用基类构造函数初始化,teacher_name应该使用派生类构造函数初始化。我是C ++的新手,所以如果这样的话不可能,请告诉我。

1 个答案:

答案 0 :(得分:0)

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

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