当派生类和基类都具有参数化构造函数时,如何初始化派生类的对象? [英] How to initialize an object of derived class when the derived class and base class both have parameterized constructors?
本文介绍了当派生类和基类都具有参数化构造函数时,如何初始化派生类的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在初始化对象时遇到问题。
以下是一段代码,
#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':没有适当的默认构造函数
我知道,由于派生类和基类都只有参数化的构造函数,我需要初始化基类对象在派生类构造函数中。但我不知道该怎么做。
任何人都可以告诉我上面的代码中有什么错误。
解决方案
public:
Derived(char a):Base(/ * int Parameter * /),m_a(a)
{
}
I am facing problem in initializing objects. Following is a piece of code,
#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();
}
Compiling the above code gives the following error, error C2512: 'Base' : no appropriate default constructor available
I know that since derived class and base class both have only parametrized constructors i need to initialize the base class object in derived class constructor. But i don't know how to do it. Can anyone please tell me as to what is wrong in the above code?
解决方案
public:
Derived(char a):Base(/*int Parameter*/),m_a(a)
{
}
这篇关于当派生类和基类都具有参数化构造函数时,如何初始化派生类的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文