如何为每个派生类存储一个幻数,然后可以从基类访问该幻数?
class User {
public:
int v() {
return min_pass_len;
}
static const int min_pass_len = 10;
};
class AdminUser : public User {
public:
int w() {
return min_pass_len;
}
static const int min_pass_len = 42;
};
那么
int main() {
AdminUser a;
std::cout << a.v() << " why? " << a.w() << std::endl;
return 0;
}
我可以以某种方式避免额外的方法调用吗?我也对其他解决方案、最佳实践感兴趣。谢谢!
class User {
public:
int v() {
return min_pass_len;
}
static const int min_pass_len = 10;
};
class AdminUser : public User {
public:
int w() {
return min_pass_len;
}
static const int min_pass_len = 42;
};
Then
int main() {
AdminUser a;
std::cout << a.v() << " why? " << a.w() << std::endl;
return 0;
}
Can I somehow avoid the extra method call? I'm also interested in other solutions, best practices. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
只需使用返回不同数字的虚拟方法,跳过静态变量。
Just use a virtual method that returns a different number, skip the static var.
如果你想为不同的派生类使用不同的常量,你应该像这样模板化基类:
If you want to have a different constant for different derived classes, you should templatize the base class like so:
您缺少
virtual
关键字。在 C++ 中,方法默认情况下不是虚拟的,就像在其他一些编程语言(例如 Java)中那样。请尝试以下操作:如果您想完全摆脱该方法,请使用 Sanjit 提到的“奇怪地重复出现的模板模式” 或将常量而不是将其嵌入到类中。我正在考虑类似于 std::numeric_limits 的实现方式:
我通常更喜欢第一种方法,因为当您有指向实例的指针时它会起作用。后一种方法几乎没有那么有用,因为您无法使用它从实例中提取常量而不求助于编写自由函数,即使这样您也失去了动态类型方面。
这种方法的问题在于,如果您在第一个代码段中使用
p
调用getPasswordLength(p)
,则会得到错误的结果。You are missing the
virtual
keyword. In C++ methods are not virtual by default like they are in some other programming languages (e.g., Java). Try the following instead:If you want to get rid of the method altogether, then either use the example of the "curiously reoccuring template pattern" mentioned by Sanjit or externalize the constant instead embedding it within the class. I was thinking of something similar to how
std::numeric_limits
is implemented:I usually prefer the first approach since it works when you have a pointer to an instance. The latter method isn't nearly as useful since you cannot use it to extract the constant from an instance without resorting to writing a free function and even then you loose the dynamic typed aspect.
The problem with this approach is that you would get the wrong result if you called
getPasswordLength(p)
usingp
in the first snippet.最佳实践建议使用
virtual
函数(这就是引入它们的原因,以使旧代码能够调用新代码):Howerer,一个在基类中定义的简单变量类,但在每个派生构造函数中重写会更快,并且会消除任何调用(因为它将被内联):
Best practices would recommend use of
virtual
function (this is why they were introduced, to make old code able to call new code):Howerer, a simple variable defined in the base class, but rewritten in each derived constructor would be faster and would eliminate any call (since it would be inlined):