未定义的参考,为什么

lih*_*hao 3 c++ templates

g ++:对'A :: sc'的未定义引用,为什么?但声明a = sc是可以的.因为模板?

#include <iostream>

template<typename T>
inline const T &min(const T &left, const T &right)
{
     return (left < right ? left : right);
}

class A 
{
public:
   static const size_t sc = 0;
   A() 
    {   
      size_t tmp = 0;
      size_t a = sc; 
      size_t b = min(sc, tmp);
    }   
};

int main()
{
  A a;
  return 0;
}                                                                                    
Run Code Online (Sandbox Code Playgroud)

R S*_*ahu 8

当你有

static const size_t sc = 0;
Run Code Online (Sandbox Code Playgroud)

作为集体成员,它仍然是一个声明.如果仅在程序中使用其值,则无需定义它.但是,如果您通过引用使用它,则必须使用以下命令定义它:

const size_t A::sc;
Run Code Online (Sandbox Code Playgroud)

这条线

  size_t a = sc; 
Run Code Online (Sandbox Code Playgroud)

sc按价值使用但行

  size_t b = min(sc, tmp);
Run Code Online (Sandbox Code Playgroud)

sc以引用方式使用.因此,sc需要定义.

  • 更有趣的事实:`min(+ sc,tmp)`不会触发错误;) (3认同)