【问题标题】:Compilation failed, c++ program with static variable as private member variable [duplicate]编译失败,将静态变量作为私有成员变量的c ++程序[重复]
【发布时间】:2012-10-29 16:23:50
【问题描述】:

可能重复:
undefined reference to static member variable
What is an undefined reference/unresolved external symbol error and how do I fix it?

#include<iostream>
using namespace std;

class abc {

    private:
    static int a ;

    public:

    abc(int x) {
        a = x;
    }

    void showData() {
        cout<<"A = "<<a<<endl;
    }
};

int main() {
    abc a1(4);
    abc a2(5);

    a1.showData();
    a2.showData();

    return 0;
}

当我尝试在 Ubuntu 上使用 GCC 编译器编译这个函数时。我收到以下错误。

/tmp/ccCKK2YN.o: In function `main':
static1.cpp:(.text+0xb): undefined reference to `Something::s_nValue'
static1.cpp:(.text+0x14): undefined reference to `Something::s_nValue'
collect2: ld returned 1 exit status
Compilation failed.

以下代码运行良好

#include<iostream>
using namespace std;

class Something
{
public:
    static int s_nValue;
};

int Something::s_nValue = 1;

int main()
{
    Something cFirst;
    cFirst.s_nValue = 2;

    Something cSecond;
    std::cout << cSecond.s_nValue;

    return 0;
}

这是因为静态成员变量在通过对象访问它们之前需要显式初始化。为什么会这样?

【问题讨论】:

标签: c++ gcc ubuntu static-members


【解决方案1】:

static int s_nValue; 没有分配任何存储空间来存储 int,它只是声明它。

你在内存中分配某个地方来存储变量:

int Something::a=0;

【讨论】:

  • int Something::a; 会做什么?
  • 不确定静态成员是否自动初始化:未定义值或 0 取决于。
  • 一般来说,所有静态存储变量(全局变量等——包括静态成员)都是值初始化的——在这种情况下是0
  • 但是我使用构造函数来初始化静态变量。这有什么问题?
  • 您的代码中没有任何构造函数。
【解决方案2】:

The declaration of a static data member in the member list of a class is not a definition. You must define the static member outside of the class declaration, in namespace scope.

this thread

简而言之,静态成员需要在.cpp 文件中的某处进行初始化,以便编译器为其分配空间。声明如下所示:

int abc::a = 0;

【讨论】:

  • 但是我使用构造函数来初始化静态变量。这有什么问题?
  • 您可以像以前一样在构造函数中为静态变量赋值,但您仍然需要在.cpp 文件中定义它。
【解决方案3】:

这是因为静态成员在类的所有实例之间共享,因此需要在一个地方声明它们。

如果您在类声明中定义静态变量,那么该文件的每个include 都会对该变量进行定义(这与static 的含义相反)。

因此,您必须在 .cpp 中定义静态成员。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-16
    • 1970-01-01
    相关资源
    最近更新 更多