在派生类的构造函数中初始化没有默认构造函数的基类 [英] Initialize base class with no default constructor in constructor of derived class

查看:730
本文介绍了在派生类的构造函数中初始化没有默认构造函数的基类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个子类 secondary ,它可以与参数一起使用,也可以覆盖类 primary 。现在我得到

I'm trying to create a subclass secondary which could be used with a parameter as well as it's overriding class primary. Now I get


没有匹配的函数可以调用

no matching function to call

错误。有人可以帮帮我吗?

error. Could someone help me?

我的代码:

primary.h:

My code:
primary.h:

#ifndef PRIMARY_H
#define PRIMARY_H


class primary
{
    public:
        primary(int x);
        virtual ~primary();
    protected:
    private:
        int primary_x;
};

#endif // PRIMARY_H

primary.cpp:

primary.cpp:

#include "primary.h"

primary::primary(int x)
{
    primary_x = x;
}

primary::~primary()
{
    //dtor
}

secondary.h:

secondary.h:

#ifndef SECONDARY_H
#define SECONDARY_H
#include "primary.h"


class secondary : public primary
{
    public:
        secondary();
        virtual ~secondary();
    protected:
    private:
};

#endif // SECONDARY_H

secondary.cpp:

secondary.cpp:

#include "secondary.h"

secondary::secondary()
{
    //ctor
}

secondary::~secondary()
{
    //dtor
}


推荐答案

因为您没有默认构造函数,编译器会抱怨它无法创建对象 primary ,你应该在 secondary 构造函数中添加一个参数/给它一个默认值:

Because you don't have a default constructor the compiler complains that it can't create an object for primary, you should either add a parameter to the secondary constructor / give it a default value:

class secondary : public primary
{
    public:
        secondary(int x);
        virtual ~secondary();
    protected:
    private:
};

然后调用基类构造函数:

And then call the base class constructor:

secondary::secondary(int x) : primary(x)
{
    //ctor
}

或者:

secondary::secondary() : primary(5)
{
    //ctor
}

或者只为主要添加默认构造函数:

Or just add a default constructor for primary:

class primary
{
    public:
        primary(int x);
        primary() : primary_x(0) {}
        virtual ~primary();
    protected:
    private:
        int primary_x;
};

这篇关于在派生类的构造函数中初始化没有默认构造函数的基类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆