简体   繁体   English

C ++静态类成员初始化

[英]C++ Static Class Member Initializing

I'm new to C++ and still in learning phase, so this may be a simple and probably dumb question to you ;( 我是C ++的新手,仍然处于学习阶段,所以这对您来说可能是一个简单的问题,可能是愚蠢的;(

From other questions and answers on the board, I learned that it is customary and preferred to initialize the private static class data member in the cpp file along with the other member function definitions. 从板上的其他问题和答案中,我了解到习惯并首选的方法是初始化cpp文件中的私有静态类数据成员以及其他成员函数定义。

However, could it be possible to initialize the member function as global variable in main.cpp? 但是,是否可以在main.cpp中将成员函数初始化为全局变量? Since all objects should share one static data member, why not just initialize it there? 由于所有对象应该共享一个静态数据成员,为什么不在那里直接对其进行初始化? (I would think initializing it in main itself, but I would guess this would spit out a compilation error) (我想初始化它本身,但是我想这会吐出编译错误)

Could you please explain if this is technically not plausible or just not done conventionally. 您能否解释一下这在技术上是不合理的还是只是传统上没有做到。 Since the static data member is initialized in class cpp file as a global variable anyways, I do not see a reason why initializing it in main cpp will fail. 由于静态数据成员无论如何都是在类cpp文件中初始化为全局变量的,因此我看不到在主cpp中初始化它失败的原因。 Please advise. 请指教。

Suppose following header file class.hpp 假设以下头文件class.hpp

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

and following source file class.cpp 及以下源文件class.cpp

#include "class.hpp"
// nothing here

and following main source file main.cpp 并跟随主源文件main.cpp

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

Now, compile class.cpp -> class.obj , main.cpp -> main.obj , and link class.obj main.obj -> executable . 现在,编译class.cpp -> class.objmain.cpp -> main.obj并链接class.obj main.obj -> executable It works as expected. 它按预期工作。 But suppose, you came up with different project ( anothermain.cpp ), that will use same class.hpp . 但是假设您想出了另一个项目( anothermain.cpp ),它将使用相同的class.hpp

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

Going through same compilation process results in link error 经历相同的编译过程会导致链接错误

unresolved external symbol "public: static int C::answer" 未解析的外部符号“ public:static int C :: answer”

So, to answer your question. 因此,回答您的问题。 It is possible. 有可能的。 The linker does not care which object file contains definition for that value (as long as it's defined only once ). 链接器不在乎哪个对象文件包含该值的定义(只要定义一次 )。 However, I would not recommend it. 但是,我不建议这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM