C ++静态类成员初始化

时间:2015-03-16 08:43:29

标签: c++ class static member

我是C ++的新手并且还处于学习阶段,所以这对你来说可能是一个简单而且可能是愚蠢的问题;(

从董事会的其他问题和答案中,我了解到习惯性和优先考虑在cpp文件中初始化私有静态类数据成员以及其他成员函数定义。

但是,是否可以在main.cpp中将成员函数初始化为全局变量?由于所有对象应共享一个静态数据成员,为什么不在那里初始化它? (我想在main中初始化它,但我猜这会吐出编译错误)

请您解释一下这在技术上是不合理的还是传统上没有做到的。由于静态数据成员在类cpp文件中初始化为全局变量,我没有看到为什么在main cpp中初始化它会失败的原因。请指教。

1 个答案:

答案 0 :(得分:1)

假设以下头文件class.hpp

#pragma once // sort of portable
struct C // to make the example shorter.
{
    static int answer;
};

并关注源文件class.cpp

#include "class.hpp"
// nothing here

并跟随主要源文件main.cpp

#include <iostream>
#include "class.hpp"
int C::answer = 42;
int main()
{
    std::cout << "And the answer is " << C::answer << "." << std::endl;
}

现在,编译class.cpp -> class.objmain.cpp -> main.obj和链接class.obj main.obj -> executable。它按预期工作。但是假设您想出了不同的项目(anothermain.cpp),它将使用相同的class.hpp

#include "class.hpp"
int main()
{
    std::cout << "And the answer is " << C::answer << "." << std::endl;
}

通过相同的编译过程会导致链接错误

  

未解析的外部符号&#34; public:static int C :: answer&#34;

所以,回答你的问题。有可能的。链接器不关心哪个目标文件包含该值的定义(只要它定义仅一次)。但是,我不推荐它。