簡體   English   中英

C ++類方法包含對靜態變量的未定義引用

[英]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關鍵字,可以將其限制為內部鏈接。

參見: http : //en.cppreference.com/w/cpp/language/static

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM