C++初始化常量和继承
我想在子类中初始化常量,而不是基类。并使用它来摆脱动态内存分配(我已经知道数组大小,并且会有一些具有不同常量的子类)。
所以我尝试:
class A {
public:
const int x;
A() : x(0) {}
A(int x) : x(x) {}
void f() {
double y[this->x];
}
};
class B : A {
B() : A(2) {}
};
非常简单,但编译器说:
错误 C2057:预期的常量表达式
我怎样才能对编译器说它确实是一个常量?
I want to initialize constant in child-class, instead of base class. And use it to get rid of dynamic memory allocation (I know array sizes already, and there will be a few child-classes with different constants).
So I try:
class A {
public:
const int x;
A() : x(0) {}
A(int x) : x(x) {}
void f() {
double y[this->x];
}
};
class B : A {
B() : A(2) {}
};
Pretty simple, but compiler says:
error C2057: expected constant expression
How can I say to compiler, that it is really a constant?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
但它不是一个常数。它仍然可以由构造函数修改。数组的大小只允许使用编译时常量。当编译器说“常量表达式”时,它并不是指返回常量值的表达式,而是指常量,例如“52”或“45”或类似的内容。
请改用 std::vector 。
编辑:响应“我已经知道数组大小,并且会有一些具有不同常量的子类”,
唯一的方法是使用模板。
It isn't a constant though. It can still be modified by the constructor. Only a compile time constant is allowed for the size of an array. When the compiler says "constant expression", it is not meaning an expression which returns a constant value, but an constant, such as "52" or "45" or something along those lines.
Use
std::vector
instead.EDIT: In response to "I know array sizes already, and there will be a few child-classes with different constants"
The only way to do that is to use a template.
使用以下模板可以实现您期望的行为。
请注意,这实际上是不可靠的、令人厌恶的,只能用作“样本”。使用
std::vector
代替。The behaviour you expect could be achieved using the following template.
Note that this is actually unreliable, disgusting and could be used only as "a sample". Use
std::vector
instead.先有“常”,再有“常”。如果您想像这样在堆栈上分配一个数组,编译器在编译时需要数组的长度,并且根据您在那里给出的内容,它无法计算出该长度。有趣的是,gcc 支持一个扩展(标准 C++ 不支持),该扩展允许可变长度的堆栈分配。
There's "constant", and then there's "constant". If you want to allocate an array on the stack like that, the compiler needs the length of the array at compile time, and based on what you've given there it can't figure that out. Interestingly, gcc supports an extension (not supported in standard C++) that allows for stack allocation for variable lengths.
我不知道它是否适合您的目的,但一种可能性是将其设为模板参数:
在这种情况下,您可能希望在 B 中创建 A 的实例,而不是使用继承。
另一种明显的可能性是使用 tr1::array 对象来代替。这也是一个模板,所以想法几乎相同,但它已经编写、测试和运行,因此您可以避免这一切。如果您的编译器不提供 TR1 类,Boost 有一个基本一致的实现 (
boost::array
)。I don't know if it will work for your purposes, but one possibility would be to make it a template parameter:
In this case, you'd probably want to create an instance of A in B instead of using inheritance.
The other obvious possibility would be to use a
tr1::array
object instead. This is is also a template, so the idea is pretty much the same, but it's already written, tested and working so you can avoid all that. If your compiler doesn't supply TR1 classes, Boost has a mostly conforming implementation (boost::array
).