如何强制基类构造函数在派生类中被调用? [英] how to force base class constructors to be called in derived classes?

查看:307
本文介绍了如何强制基类构造函数在派生类中被调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本c ++问题我相当肯定。如果我有一个基本类与一个构造函数没有参数,只是初始化一些受保护的成员,派生类也立即调用这个基本构造函数太多,如果它匹配的参数(希望但不太可能的想法),如果不是,有一种方法来强制它从派生类自动调用所述基础构造函数,而不必显式地告诉它这样做在派生类中?我问,因为我写一个包装的各种,有一些受保护的成员,我想初始化为特定的值,然后我想导出和操作这个基类,我的需要,但我不喜欢外部用户必须记住显式调用基础构造函数或在自己的构造函数中设置这些值。

basic c++ question i'm fairly sure. if i have a base class with a constructor that takes no parameters, and just initializes some of the protected members, does a derived class instantly call this base constructor too if it matches the parameters (wishful but unlikely thinking), and if not, is there a way to force it to automatically call said base constructor from the derived class WITHOUT having to explicitly tell it to do so in the derived class? I ask because i'm writing a wrapper of sorts and there are some protected members that i want initialized to specific values initially, and then i want to derive and manipulate this base class to my needs, but i wouldn't like an outside user to have to remember to explicitly call the base constructor or set these values within their own constructor.

推荐答案

例如:

class A
{
public:
   A() { std::cout << "A"; }
};

class B : A
{
public:
   B() {}
};

int main()
{
   B b;
   return 0;
}

将输出:

A

您可以从派生类调用不同的构造函数:

By "explicitly stated otherwise" I mean that you can call a different constructor from the derived class:

class A
{
public:
   A() { std::cout << "A"; }
   A(int) { std::cout << "AAA"; }
};

class B : A
{
public:
   B() : A(1) {}  //call A(int)
};

int main()
{
   B b;
   return 0;
}

会输出

AAA

重要没有默认构造函数(你声明一个非默认构造函数而不是默认构造函数)或默认构造函数不可见(标记为 private ),则需要显式调用派生类中的可用构造函数。

Important if you don't have a default constructor (you declare a non-default constructor and not a default one) or the default constructor is not visible (marked as private), you need to explicitly call an available constructor in the derived class.

这篇关于如何强制基类构造函数在派生类中被调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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