[英]C++ - Initialze static variable with global scope
我在頭文件中包含了一個靜態的 c++ 字符串數組。 當我嘗試在源文件中訪問它時出現段錯誤。
這是詳細信息。 操作系統:Linux 編譯器:g++
作業.hpp
static string values[2] = {"hello","welcome"};
class Job
{
public:
void getValues();
};
作業.cpp
#include "job.hpp"
void Job::getValues()
{
// Seg Fault Here
// i value is either 0 or 1 and is based on some external flag
cout << values[i] << endl;
}
我相信 values 數組沒有被初始化。 此代碼適用於 AIX 上的 xlc++ 編譯器。 是否有任何 g++ 編譯器標志來初始化靜態變量。
為什么不把你的“值”數組變成類的靜態屬性? 像下面這樣的東西可能會起作用。
作業.h
#ifndef JOB_H
#define JOB_H
#include <string>
#include <iostream>
using namespace std;
class Job
{
public:
Job();
void getValues() const;
//declare static variable in .hpp file
static string values[2];
private:
};
#endif
作業.cpp
#include "job.h"
//initialize variable in .cpp file
string Job::values[2]={"hello", "welcome"};
Job::Job(){}
void Job::getValues() const
{
cout << values[i] << endl;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.