【问题标题】:C++ - global variable scopeC++ - 全局变量范围
【发布时间】:2014-04-23 00:17:15
【问题描述】:

我有一个任务:有很多.cpp文件,所以我必须在每个文件中找到所有全局变量的声明。所以我有,例如,这部分代码:

class word {
public:
    word(string code0, string text0, int weight0) : code(code0), text(text0),
    weight(weight0), index(word::num) {};
    friend bool operator<(word w1, word w2);
    friend ostream &operator<<(ostream &stream, word w);
    friend bool wordWithCode::operator()(const word &w);
    static bool convertChars(char *inp, char *out);
    inline bool checkCode(char *check) { return !strcmp(code.c_str(),check); };
    inline const char* getText() { return text.c_str(); };
    inline void useIt(set< word >::iterator &i) {
        cout << this->text;
        if (code[0]!='1') {
            word::num++;
            word::words.insert(word(this->code,this->text,this->weight+1));
            word::words.erase(i);
        }
        return;
    };
    static set< word > words;
    string code;
    string text;
    int weight;
    static int num;
private:
    int index;
};

int word::num = 0;
set< word > word::words;

int main(){
    ...
    return 0;
}

所以我的问题是:静态变量 word::num 和 word::words 是全局的吗?以及如何正确识别他们的名字(只是“num”或“word::num”)?

【问题讨论】:

    标签: c++ class oop variables scope


    【解决方案1】:

    是的,它们是单个全局变量,您可以在 word 函数之外将它们引用为 word::numword::words。在 word 的函数中,您可以像 numwords 一样引用它们

    【讨论】:

      猜你喜欢
      • 2010-10-07
      • 2012-04-29
      • 2017-02-17
      • 1970-01-01
      • 1970-01-01
      • 2012-11-20
      • 2013-05-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多