无效使用非静态数据成员

Say*_*iss 0 c++ syntax

这是我自己实现的堆(用于算法竞赛).有一些我无法从中恢复的编译错误......

\Map_Heap.cpp|13|error: invalid use of non-static data member 'MapHeap<DT>::nv'|
\Map_Heap.cpp|19|error: from this location|
Run Code Online (Sandbox Code Playgroud)

码:

#include<cstdio>
#include<cstring>
const int HEAP_SIZE=10005;
template<class DT>
struct MapHeap
{
    DT f[HEAP_SIZE+5];
    int mp1[HEAP_SIZE+5];//val -> index
    int mp2[HEAP_SIZE+5];//index -> val
    int nv;///line 13
    MapHeap():nv(0)
    {
        memset(mp1,-1,sizeof(mp1));
        memset(mp2,-1,sizeof(mp2));
    }
    void print(int n=nv)//line 19
    {
        for(int i=1;i<=n;i++) printf("%d ",f[i]);
        puts("");
        for(int i=1;i<=n;i++) printf("%d ",mp1[i]);
        puts("");
        for(int i=1;i<=n;i++) printf("%d ",mp2[i]);
        puts("");
    }
};
Run Code Online (Sandbox Code Playgroud)

Oli*_*rth 8

它只是说你不能在成员变量上建立一个默认参数.请考虑使用重载:

void print() { print(nv); }
void print(int n) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

  • @ Mr.TAMER.其实,是.参见8.3.6,第9节:"非静态成员不得在默认参数表达式中使用". (6认同)
  • 是否在标准中明确提到"你不能在成员变量上建立默认参数? (2认同)