[英]C++ Class Method contains Undefined Reference to a Static Variable
在C ++中,我试图实现一个枚举,该枚举将被接受为方法中的参数,并始终接收链接错误(未定义的引用)。 让我提供我的标头,实现和示例主要执行。 另请注意,我使用的是Makefile,如果您认为问题出在Makefile中,则可以提供。
标头:
// 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关键字,可以将其限制为内部链接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.