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

c++ publicly inherited class member cannot be used as default argument(c++ 公开继承的类成员不能用作默认参数)
本文介绍了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...
}

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)