静态成员和consts

mat*_*ati 2 c++ static const

class a
{
protected:
  const int _ID;

public:
  a::a(int id){};
  a::top(int num);
};

class b : public a
{
  static int ok;
  b::b(int id):a(id){};
  a::top(ok);
}

int main()
{
  int t=5;
  b opj=b(t);
}
Run Code Online (Sandbox Code Playgroud)

首先,为什么我得到这个编译错误,只有当我删除const时解决

非静态const成员'const int Student :: _ ID',不能使用默认赋值运算符 - 实例化自'void std :: vector :: _ M_insert_aux(__ gnu_cxx :: __ normal_iterator,const _Tp&)[with _Tp = Student,_Alloc =的std ::分配器]"

第二

我有另一个问题

未定义的引用b :: ok

Jam*_*ran 5

第二个: b::ok已经宣布,但没有定义.某处,(最好是b.cpp),你需要添加:

  int b::ok;
Run Code Online (Sandbox Code Playgroud)

至于你的第一个问题, _IDconst,它的值不能改变 - 但是,你永远不会给它一个值开始.你必须为它分配一个初始值:

  protected:
      const int _ID = 1234;
Run Code Online (Sandbox Code Playgroud)

现在,你真的应该定义_ID,就像我们使用b :: ok一样,但是因为它是const,编译器可能会让你在没有这样做的情况下逃脱(某些条件适用).