Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/138.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
基于C++中的决策调用父级初始化器_C++_Constructor_Initialization - Fatal编程技术网

基于C++中的决策调用父级初始化器

基于C++中的决策调用父级初始化器,c++,constructor,initialization,C++,Constructor,Initialization,我有这个代码,用于调用C++中的父初始化器。< /P> #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 st

我有这个代码,用于调用C++中的父初始化器。< /P>
#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) {
    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")) {}
B(const string& b) : A(modify(b)) {}

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

只要您调用同一个构造函数并为初始值设定项使用相同的签名,您就可以使用Casey的答案。但是,如果您想执行以下操作:

B(const string& b) {
    if (...) {
        A(b + "x");
    } else {
        A(foo, bar);
    }
}
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";
    }
};

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

如果您想要执行复杂的逻辑,最好将其放在单独的函数中:

std::string modify(const std::string &b) {
    if (...) {
        return b + "x";
    } else {
        return b + "y";
    }
}
然后,您可以在初始值设定项列表中使用该函数:

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

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

B(const string& b) {
    if (...) {
        A(b + "x");
    } else {
        A(foo, bar);
    }
}
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的答案外,我还将把modify函数设为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中,而不是作为外部的单独函数。它将更加面向对象。

您不能像调用函数一样调用函数的构造函数。