C++类方法包含对静态变量的未定义引用

C++ Class Method contains Undefined Reference to a Static Variable

本文关键字:未定义 引用 变量 静态 类方法 包含 C++      更新时间:2023-10-16

>在C++中,我正在尝试实现一个枚举,以被接受为方法中的参数,并始终收到链接错误(未定义的引用)。让我提供我的标头、实现和示例主执行。另请注意,我使用的是生成文件,如果您认为问题在生成文件中,可以提供该文件。

页眉:

// Make sure definitions are only made once
//
#ifndef MYTEST_H
#define MYTEST_H
// System include files
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
// Declare class definitions 
//
class MyTest {
// Public data
//
public:
// Define debug_level choices
//
enum DBGL {FULL = 0, PARTIAL, BRIEF, NONE};
// Define a debug_level variable
//
static DBGL debug_level_d;
// Define public method set_debug that sets debug level to a specific value
//
bool set_debug(DBGL x_a);
// End of include file
//
#endif

这是我的实现文件"mytest_00.cc"。在这里,我尝试将枚举类型"DBGL"定义为调试级别。然后我试图接受它作为方法"set_debug"中的一个参数。

#include "mytest.h"
// Implementations of methods in MyTest
// Declare debug_level
//
static MyTest::DBGL debug_level_d = MyTest::FULL;
// Implement set_debug method to set the debug_level_d
// FULL = 0, PARTIAL = 1, BRIEF = 2, NONE = 3
//
bool MyTest::set_debug(MyTest::DBGL x_a) {
// Set debug_level_d to the argument provided
//
debug_level_d = x_a;
// exit gracefully
//
return true;
}

目标是通过执行如下操作来测试主函数中的类 'mytest':

MyTest Test;
Test.set_debug(FULL);

此代码会将变量"debug_level_d"设置为传递的参数。

我在编译时收到的错误如下:

g++ -O2 -c mytest.cc -o mytest.o
g++ -O2 -c mytest_00.cc -o mytest_00.o
g++ -g -lm mytest.o mytest_00.o -o mytest.exe
mytest_00.o: In function `MyTest::set_debug(MyTest::DBGL)':
mytest_00.cc:(.text+0x12): undefined reference to `MyTest::debug_level_d'
collect2: error: ld returned 1 exit status
make: *** [mytest.exe] Error 1

任何有助于理解为什么会发生此错误的帮助将不胜感激。我已经坚持了一天了。如果有任何细节需要进一步澄清,请告诉我。

谢谢。

在.cpp文件中定义字段时,不应使用 static 关键字,而应在类中声明字段时使用。 请注意,在代码注释中,您的"声明"和"定义"方式错误。

此外,在定义成员时,需要使用类名对其进行限定。

所以.cpp定义应该是:

MyTest::DBGL MyTest::debug_level_d = MyTest::FULL;

通过在定义中使用 static 关键字,可以将其限制为内部链接。

请参阅: http://en.cppreference.com/w/cpp/language/static