c++ 公共继承的类成员不能用作默认参数 [英] c++ publicly inherited class member cannot be used as default argument

查看:30
本文介绍了c++ 公共继承的类成员不能用作默认参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题的示意图...

A schematic of my problem...

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

这篇关于c++ 公共继承的类成员不能用作默认参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆