【发布时间】:2016-04-08 18:52:59
【问题描述】:
Foo 继承 std::array<int, 2>。是否可以将数组填充到 Foo 的构造函数的初始化列表中?
如果是这样,以下语法的有效替代方法是什么?
// Foo is always an array of 2 ints
struct Foo: std::array<int, 2>
{
Foo() {}
Foo(const int & x, const int & y) : std::array<int, 2> { x, y } {}
}
我尝试添加一对额外的大括号,它适用于 g++,但不适用于 VC2015 编译器:
#include <array>
#include <iostream>
struct Foo : std::array<int, 2>
{
Foo() {}
Foo(const int & x, const int & y) : std::array<int, 2> {{ x, y }} {}
};
int main()
{
Foo foo(5, 12);
std::cout << foo[0] << std::endl;
std::cout << foo[1] << std::endl;
system("PAUSE");
}
并得到以下错误:https://i.gyazo.com/4dcbb68d619085461ef814a01b8c7d02.png
【问题讨论】:
-
为什么
Foo继承自std::array? -
在我的应用程序中,它将是一个带有 GetX() SetY() 函数等的点/向量类。对我来说,这比带有 x,y,z 数据成员的结构更有意义,因为它允许我删除每个维度的重复代码。
-
这当然取决于您如何设计事物。但我要说的是,继承并不是大多数工作的最佳工具(blog.codinghorror.com/inherits-nothing,而且与 C# 不同,大多数 C++ 标准库并不是真正设计用于继承的)。虽然您可以从
std::array继承,但请注意它没有virtual函数,这意味着您几乎永远不会通过std::array指针或引用与您的Foo交互;但这没关系,因为std::array的析构函数是非虚拟的,所以当你销毁你的对象时,你需要知道你真的有一个Foo。 -
但是在基类中没有任何
virtual方法,我个人认为没有太多使用继承的理由。 -
最好的选择是什么?我试图避免使用 C 数组。
标签: c++ templates constructor initializer-list