C ++在初始化列表中的基类初始化之前调用函数 [英] C++ Calling a function before base-class initialization in the initialization list

查看:122
本文介绍了C ++在初始化列表中的基类初始化之前调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个项目中,我有类B ,它是从类A派生的,其中 Class A 具有不可访问的默认构造函数。

In a project, I have class B which is derived from class A, where class A has an inaccessible default constructor.

Class B 设置如下:

class B : public A
{
private:
    void SetupFunction() { /*Crucial code*/ }
public:
    B() : A(Value) {}
}

假设对于 SetupFunction()在初始化期间之前调用 A(Value)构造函数,我将如何实现呢?

Supposing it is crucial for SetupFunction() to be called during initialization before the A(Value) constructor, how would I go about achieving this? Is it possible?

我在Windows 7上使用 Code :: Blocks 13.12

I'm using Code::Blocks 13.12 on Windows 7

推荐答案

您可以使 SetupFunction()返回随后传递给初始化的值 A ,例如:

You could make SetupFunction() return the value that's then passed to initialise A, e.g:

class B : public A
{
private:
    int SetupFunction() { /*Crucial code*/ return Value; }
public:
    B() : A(SetupFunction()) {}
}

或者如果不想更改 SetupFunction(),则使用逗号运算符:

Or use the comma operator if you don't want to change SetupFunction():

class B : public A
{
private:
    void SetupFunction() { /*Crucial code*/ }
public:
    B() : A((SetupFunction(), Value)) {}
}

这篇关于C ++在初始化列表中的基类初始化之前调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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