【问题标题】:C++ Static Variable giving error [duplicate]C ++静态变量给出错误[重复]
【发布时间】:2018-07-31 11:44:36
【问题描述】:

我正在学习 C++,但我正在研究的实验室遇到了一个奇怪的问题。我似乎没有正确引用事物的地方是我的猜测。

它基本上会抛出一个错误,例如找不到类头文件中声明的静态 int nCounters。

//counter.h的开始

class Counter
{

private:
  int counter;
  int limit;
  static int nCounters;

public:
  Counter(int x, int y);
  void increment();
  void decrement();
  int getValue();
  int getNCounters();

};

//counter.h结束

//counter.cpp的开始

#include "counter.h"

Counter::Counter(int x, int y)
{
    counter = x;
    limit = y;
    nCounters++;
}

void Counter::increment()
{
    if (counter < limit)
    {
        counter++;
    }
}

void Counter::decrement()
{
    if (counter > 0)
    {
        counter--;
    }
}

int Counter::getValue()
{
    return counter;
}

int Counter::getNCounters()
{
    return nCounters;
}

//counter.cpp结束

//counter_test.cpp的开始

#include <iostream>
#include "counter.cpp"
using namespace std;
int main(){
    Counter derp(5,5);

    cout << derp.getValue();

    return 0;
}

//counter_test.cpp结束

【问题讨论】:

  • 如果我删除 static 它编译并运行得很好。这一定是我在这里不明白的东西。
  • 通过“C++ 未定义引用静态成员”之类的搜索可以找到数十个甚至数百个已回答的 Stack Overflow 问题。
  • @aschepler Google 搜索 未定义的引用静态变量 c++ 站点:stackoverflow.com 说“大约 48,200 个结果”

标签: c++ oop static-variables


【解决方案1】:

您需要define static 变量。 static int nCounters; 只是一个声明而不是定义。

这样定义

int Counter :: nCounters;

例如

class Counter {
        private:
                static int nCounters; /*declaration */
        public:
                /* Member function of class */
};
int Counter :: nCounters;/*definition, this is must  */
int main() {
        /* some code **/
        return 0;
}

【讨论】:

  • Awesome 在我的 counter.cpp 文件中添加后完美运行。我知道我一定是在什么地方遗漏了什么。
【解决方案2】:

由于此变量在所有类中都是相同的,并且在实例化 Counter 时未定义,因此与普通成员变量不同,您必须在代码中的某处添加以下行(最好放在 counter.cpp 中):

Counter::nCounters = 0;

这设置了nCounters的定义和初始值。

另一方面,#include "counter.cpp" 是不好的做法。而是 #include "counter.h" 并将 .cpp 文件链接到您的可执行文件。

【讨论】:

  • 我也按照您的建议做了,并将我的 counter.cpp 文件移动到 counter.h 文件的页脚。谢谢,这有点干净。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-06
  • 2015-06-12
  • 1970-01-01
  • 1970-01-01
  • 2021-04-04
  • 1970-01-01
  • 2023-03-03
相关资源
最近更新 更多