c++ - 编译失败,c++程序以静态变量为私有(private)成员变量

标签 c++ gcc ubuntu static-members

<分区>

Possible Duplicate:
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;
}

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

最佳答案

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

您在内存中的某处分配以存储变量:

int Something::a=0;

关于c++ - 编译失败,c++程序以静态变量为私有(private)成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13125662/

相关文章:

ubuntu - 以低带宽使用 RSYNC 的最佳方式是什么?

ruby-on-rails - 我应该在哪个版本的 Ubuntu 上运行我的 Rails 应用程序?

c++ - Eclipse 找不到头文件,即使设置了包含路径

c++ - swprintf 在 xcode 中使用 unicode 字符失败,但在 visual studio 中有效

linux - make-kpkg 使用 -O0 为 kgdb 构建内核

c++ - gcc:剥离未使用的功能

php - 启用 php ext-xml?

c++ - MSVC下的奇优化问题

c++ - 使用 std::deque 和 clang 编译器

c++ - 双对齐