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

后端 未结 3 1445
Happy的楠姐
Happy的楠姐 2020-12-21 05:37

A schematic of my problem...

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

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


        
3条回答
  •  轮回少年
    2020-12-21 06:16

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

提交回复
热议问题