为什么静态变量需要在C ++中声明两次 [英] Why do static variables need to be declared twice in C++

查看:256
本文介绍了为什么静态变量需要在C ++中声明两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个头文件 filepaths.h ,它定义了一些静态变量:

I have a header called filepaths.h which defines a number of static variables:

#ifndef FILEPATHS_H
#define FILEPATHS_H

class FilePaths {

public:

    static QString dataFolder();
    static QString profileFolder();

private:

    static QString dataFolder_;
    static QString profileFolder_;

};

}
#endif // FILEPATHS_H

最初看起来像这样的相关 filepaths.cpp

And I have an associated filepaths.cpp which initially looked like this:

#include "FilePaths.h"

QString FilePaths::dataFolder() {
    return dataFolder_;
}

QString FilePaths::profileFolder() {
    return profileFolder_;
}

然而,这不起作用 - 我有一个未解决的符号错误链接器错误所有静态变量。因此,我以这种方式将这些变量添加到C ++文件中:

However that didn't work - I got an "unresolved symbol error" linker error on all the static variables. So I've added these variables to the C++ file in this way:

#include "FilePaths.h"

QString FilePaths::dataFolder_ = "";
QString FilePaths::profileFolder_ = "";

QString FilePaths::dataFolder() {
    return dataFolder_;
}

QString FilePaths::profileFolder() {
    return profileFolder_;
}

然后我就不明白为什么了。

And this works, however I don't understand why.

为什么这些静态变量需要定义两次?或者也许我不是定义他们,但初始化他们?但是为什么还需要做呢?

Why do these static variables need to be defined twice? Or maybe I'm not defining them but initializing them? But still why does it need to be done? Or should I write my class differently?


推荐答案

一个是定义,另一个是声明。不同的是,声明可以出现多次,对于不在类中的变量,可能永远不会出现,而定义只能出现一次,只出现一次。

The reasons for needing separate declarations and definitions is archaic history, the kind of thing where it basically doesn't have to be that way at all but it is that way so that C++ is compatible with C, which was designed to be compiled in the 1970s.

这篇关于为什么静态变量需要在C ++中声明两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆