如何在C ++的派生类构造函数中初始化基类的const变量? [英] How can I initialize a const variable of a base class in a derived class' constructor in C++?

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

问题描述

我有一个没有构造函数的抽象C ++类。它应该是一个基类,所以其他类可以继承它。我想做的是在基类中声明一个常量变量,并在每个派生类的构造函数中初始化它,但在每个类中没有其他地方。在C ++中是合法的吗?如果是,我该怎么办呢?

I have an abstract C++ class with no constructor. It's supposed to be a base class so other classes can inherit from it. What I am trying to do is to declare a constant variable in the base class and initialize it in each derived class' constructor but nowhere else in each one of those classes. Is it legal in C++? If so, how can I do that?

推荐答案


在C ++中是否合法?

Is it legal in C++?

否。

解决方案是在你的基类中提供一个合适的构造函数 - 否则不能用过的。此外,没有理由不提供该构造函数。

The solution is to provide an appropriate constructor in your base class – otherwise it cannot be used. Furthermore, there’s no reason not to provide that constructor.

class Base {
    int const constant;
public:
    virtual ~Base() = 0; // Makes this an abstract base class.
protected:
    Base(int c) : constant(c) { }
};

// Must be implemented!
Base::~Base() { }

class Derived : public Base {
public:
    Derived() : Base(42) { }
};

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

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