c++ 公开继承的类成员不能用作默认参数

2022-01-21 00:00:00 inheritance arguments default c++

我的问题示意图...

class A
{
public:
    // etc.
protected:
    uint num;
};

class B : public A
{
public: 
    void foo(uint x = num); //bad
};

给出这个错误:

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?

推荐答案

我怀疑会发生这种情况(基于对非静态性的抱怨),因为没有 this 指针可供它使用应该从 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.

Microsoft 编译器(至少)允许您指定表达式,但不能指定非静态成员.来自 MSDN:

The Microsoft compiler (at least) allows you to specify an expression, but not a non-static member. From MSDN:

默认使用的表达式论点通常是不变的表达式,但这不是要求.表达式可以结合可见的功能当前范围,常量表达式和全局变量.这表达式不能包含本地变量或非静态类成员变量.

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...
}

相关文章