根据C++中的决策调用父级的初始值设定项

Calling parent's initializer based on decisions in C++

本文关键字:C++ 决策 调用 根据      更新时间:2023-10-16

我有这段代码在c++中调用父类初始化器

#include <iostream>
using namespace std;
class A
{
public:
    A(const string& a) {}
};
class B : public A
{
public:
    B(const string& b) : A(b) {}
};

我想我可以用父初始化器修饰一下,像这样

B(const string& b) : A(b + "!!") {}

那么,当我需要一些决策逻辑来设置父初始化项时该怎么办呢?我试过了,但我得到了错误信息。

B(const string& b) {
    if (...) {
        A(b + "x");
    } else {
        A(b + "y");
    }
}
>> ERROR 
hier.cpp: In constructor 'B::B(const string&)':
hier.cpp:16:2: error: no matching function for call to 'A::A()'

在初始化列表中进行编码:

B(const string& b) : A(b + ((...) ? "x" : "y")) {}

如果"决策逻辑"变得更复杂,您可以将其分解为一个单独的函数(通常是一个私有静态成员)。

如果你想执行复杂的逻辑,最好把它放在一个单独的函数中:

std::string modify(const std::string &b) {
    if (...) {
        return b + "x";
    } else {
        return b + "y";
    }
}

然后你可以在你的初始化列表中使用这个函数:

B(const string& b) : A(modify(b)) {}

可以在基类的构造函数中放置一个静态私有方法,如下所示:

class B : public A
{
public:
    B(const string& b) : A(initval(b)){}
private:
    static string initval(const string& b) {
        if (...)
            return b + "x";
        else
            return b + "y";
    }
};

除了sth的答案,我还将修改函数设置为b的静态方法。

std::string B::modify(const std::string &b) {
    if (...) {
        return b + "x";
    } else {
        return b + "y";
    }
}

类定义中:

static std::string B::modify(const std::string &b)

然后,使用它:

B(const string& b) : A(B::modify(b)) {}

这样做的原因是它将完全封装在B中,而不是作为外部的单独函数。它将更加面向对象。

只要调用相同的构造函数(为初始化器使用相同的签名),就可以使用Casey的答案。但是,如果您想这样做:

B(const string& b) {
    if (...) {
        A(b + "x");
    } else {
        A(foo, bar);
    }
}

那你就完蛋了。在c++中没有这样的东西。解决这个问题的唯一方法是调用默认构造函数,然后使用专门的成员函数(通常称为init()或类似的函数)进行初始化。当你有一堆不同的构造函数需要通过相互调用来实现时,你也需要同样的技术,遗憾的是,这在c++中是被禁止的。在像Objective-C这样漂亮的语言中,这两个问题都不存在。