您的位置:首页 > Web前端

类中静态变量未定义导致undefined reference to static class member问题的解决方法

2015-03-19 21:15 1091 查看
undefined reference to ***这个链接错误的花样总是层出不穷(more),这一次是找不到类中的成员。

例子1:undefined reference to VS. 类静态成员变量

在文件A.h中声明了类A与类B:
class A
{

friend class B;

static
int pa;                  // 注:这里把成员变量声明为static

}

class B

{
     public:
         void funB();
//funB()用到 A::pa;
}

问题:
gcc返回链接错误:undefined reference to 'A::pa'。然而,把类B中的pa声明为非static变量,则可以通过编译。

WHY:
先复习一下static data members in class。
[1] a single piece
of storage for a static data member, regardless of how many objects of that class you create.
[2] the static data belongs to the class. Its name is scoped inside the class and all objects share that data member.
[3] NOTE: The linker will report an error if
a static data member is declared but not defined.

所以,问题就出在:在class中,无法对static data member进行复制,即便是在构造函数中对static data member进行赋值,linker还是会报错。
因为static data member不属于任何一个对象,所以即便是在创建对象的时候进行赋值,也只能说明,这个对象对这个data member重新赋值而已。
因此,这里的undefined reference to ***,是找不到类静态成员变量的定义。

解决方法:
The definition must occur outside the class (no inlining is allowed), and only one definition is allowed.
It is common to put it in the implementation file for the class.
其实,也就是在全局的地方对静态成员变量赋值。

在上面的例子中,可在文件A.cpp中在其他函数定义之外,包括在构造函数之外,加上pa的定义,此时不需要加static前缀,但要加类名限定,也可以不赋值。
A* B::pa;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: