C ++继承公开类成员不能用作默认参数 [英] c++ publicly inherited class member cannot be used as default argument
问题描述
我的问题的示意图...
A schematic of my problem...
class A
{
public:
// etc.
protected:
uint num;
};
class B : public A
{
public:
void foo(uint x = num); //bad
};
给出了这样的错误:
gives this error:
error: invalid use of non-static data member ‘A::num’
error: from this location
为什么会这样,我能做些什么来解决此问题?
Why does this happen, and what can I do to work around this?
推荐答案
我怀疑这种情况(根据有关非staticness投诉),因为没有这个
指针它使用了解的这的B比如,它应该得到 NUM
从
I suspect this happens (based on the complaint about non-staticness) because there is no this
pointer for it to use to know which instance of B it should get num
from.
微软编译器(至少)允许您指定一个前pression,但不是非静态成员。从 MSDN :
The Microsoft compiler (at least) allows you to specify an expression, but not a non-static member. From MSDN:
前pressions
参数往往是不变
前pressions,但是这不是一个
需求。这位前pression能
结合了在可视功能
当前范围,恒
前pressions和全局变量。该
前pression不能包含本地
变量和非静态的类成员
变数。
The expressions used for default arguments are often constant expressions, but this is not a requirement. The expression can combine functions that are visible in the current scope, constant expressions, and global variables. The expression cannot contain local variables or non-static class-member variables.
的变通为此很多,其他人指出了一些。另外还有一个您可能会或可能不喜欢:
Work-arounds for this are numerous and others have pointed out a few. Here's one more which you may or may not like:
void foo(uint* x = NULL) {
uint y = (x == NULL ? num : *x);
// use y...
}
这篇关于C ++继承公开类成员不能用作默认参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!