根据C++中的决策调用父级的初始值设定项
Calling parent's initializer based on decisions in C++
我有这段代码在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这样漂亮的语言中,这两个问题都不存在。
相关文章:
- 架构决策:返回std::future还是提供回调
- 如果以下行不包含决策或分支,GDB 无法单步跳过函数
- 无法使用 ILOG CP 的 C++ API 访问决策变量
- C++设计决策:一个标头用于多个源文件...或不
- 我们可以在不使用任何控制结构的情况下从函数中返回基于决策的值
- 决策和递归函数
- 写入并加载决策树以归档C
- OPENCV随机决策森林:如何获得后验概率
- OpenCV CvSVM.predict() 决策函数值
- 导出决策树
- C++11 标准决策"shared_ptr(const weak_ptr<Y>& r) Throws bad_weak_ptr"
- 如何在C/C++中使用在R中训练的模型(决策树)
- OpenCV 决策树参数问题
- 根据运行时决策组合不同的迭代器
- 使用 z3 直接访问理论决策程序
- 高效频率计算的数据结构决策.
- 在C++中为 AI 制作决策树
- 避免使用静态布尔值上的if语句进行逻辑决策
- 如何访问决策变量:OPL/Cplex && C++
- 物理引擎的继承/接口决策