【发布时间】:2017-06-14 06:43:24
【问题描述】:
C++ 中是否有一种语法来初始化指向具有不同类型的对象的指针数组而无需额外分配?我试图在下面提供一个完整的示例。
#include "stdio.h"
class Base {
public:
Base(int cnt=1) : _cnt(cnt) {}
virtual void print() { printf("?\n"); }
protected:
int _cnt;
};
class A : public Base {
public:
A(int val, int cnt=1) : _val(val), Base(cnt) {}
void print() override { for (int i=0; i<_cnt; i++) printf("A(%d)\n", _val); }
private:
int _val;
};
class B : public Base {
public:
B(const char* val, int cnt=1) : _val(val), Base(cnt) {}
void print() override { for (int i=0; i<_cnt; i++) printf("B(\"%s\")\n", _val); }
private:
const char* _val;
};
// *** I would like to combine the following statements ***
A a = { 42, 2 };
B b = { "hi there", 3 };
Base* test[] = { &a, &b };
int main() {
for (auto *x : test) { x->print(); }
}
当我尝试时
Base* test2[] = {
&A(42, 2),
&B("hi there", 3),
};
获取临时地址时出现错误。代码需要在小型嵌入式系统上运行代码,所以我尽量避免动态分配。
希望这不是常见问题解答 ...
感谢您的帮助!
【问题讨论】:
-
不是没有动态分配
-
错误消息准确地说明了问题所在。使用
new A(42,2)。更好地使用智能指针 -
类型集有多大?它是开放的还是封闭的?
-
@StoryTeller:大约有 10 种不同类型的对象。
-
还有可以随时添加的吗?还是这组类型是封闭的?
标签: c++ arrays initialization