对类的静态成员的未定义引用 [英] Undefined reference to a static member of the class

查看:134
本文介绍了对类的静态成员的未定义引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从事一项家庭作业作业,除了我们的教授希望我们使用的令人讨厌的静态值之外,我几乎完成了所有工作:value

I am working on a homework assignment, and I have almost everything done except for this obnoxious static value that our professor wishes us to use: value

头文件包含:

private:
    static int value;

我们必须有一个函数计算值,如下:

And we have to have a function calculate the value, like so:

static void calculate()
{
    long a = 1L;
    int count = 0;

    while( a != 0 )
    {
        a = a << 1;
        count++;
    }

    value = count;
}

这实际上是使用位移位来计算长整数中的位数。

This is essentially calculating the number of bits in a long, using bit shifting.

但是,我收到错误未定义引用`Class1 :: value'

However, I am getting the error " undefined reference to `Class1::value'

谢谢!

更新:

我包括

int Class1::value = 0;

但是,现在我得到一个错误说:错误:int Class1 :: value is private

However, now I am getting an error saying "error: int Class1::value is private

推荐答案

cpp文件添加

int ClassName::value = 0;

这将为分配存储。

您在类声明中实际具有的一段代码声明此变量(使编译器知道这样的变量存在)。但是,每个变量必须声明并定义 。一个定义将确保存储被放在一个这个变量,并创建一个符号,你的编译器无法找到之前。

The piece of code that you actually have in a class declaration just declares this variable (makes the compiler aware that such a variable exists). However, each variable must be declared and defined. A definition will make sure the storage is put aside for this variable and create a symbol your compiler was unable to find before.

这篇关于对类的静态成员的未定义引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆