当派生类和基类都有参数化构造函数时,如何初始化派生类的对象?

时间:2011-09-13 10:47:24

标签: c++ constructor

我在初始化对象时遇到问题。 以下是一段代码,

#include <iostream>
#include <conio.h>
using namespace std;

class Base
{
public:
Base(int a)
{
    m_a = a;
}
private:
int m_a;

};

class Derived:public Base
{
public:
Derived(char a)
{
    m_a = a;
}
private:
char m_a;

};


void main()
{

_getch();

}

编译上面的代码会出现以下错误: 错误C2512:'Base':没有合适的默认构造函数

我知道由于派生类和基类都只有参数化构造函数,我需要在派生类构造函数中初始化基类对象。但我不知道该怎么做。 谁能告诉我上面的代码有什么问题?

2 个答案:

答案 0 :(得分:6)

    public:
    Derived(char a):Base(/*int Parameter*/),m_a(a)
    {

    }

答案 1 :(得分:0)

制作小道之后我还有一种初始化基类的方法, 以下是代码,

#include <iostream>
#include <conio.h>
using namespace std;

class Base
{
public:
Base(int a)
{
    m_a = a;
}
private:
int m_a;

};

class Derived:public Base
{
public:
Derived(int b, char a):Base(b)
{
    m_a = a;
}
private:
char m_a;

};


void main()
{
    Derived d(10,'A');

_getch();

}
相关问题