c++ publicly inherited class member cannot be used as default argument

空扰寡人 提交于 2019-11-28 08:56:51

问题


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?


回答1:


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.

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



回答2:


You can use overloading instead of default arguments.

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

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



回答3:


you can create 2 foos

foo() //use num internally

foo(int x) //use x



来源:https://stackoverflow.com/questions/2159538/c-publicly-inherited-class-member-cannot-be-used-as-default-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!