我是C++的新手,还处于学习阶段,所以这对你来说可能是一个简单而愚蠢的问题。
从黑板上的其他问题和答案中,我了解到在cpp文件中初始化私有静态类数据成员以及其他成员函数定义是一种习惯和首选。
但是,有可能在main.cpp中将成员函数初始化为全局变量吗?既然所有对象都应该共享一个静态数据成员,为什么不直接在那里初始化它呢?(我认为在main本身中初始化它,但我猜这会导致编译错误)
您能否解释一下,这在技术上是不合理的,或者只是不是按照惯例来做的。请给我建议。
发布于 2015-11-20 08:05:03
假设下面的头文件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.obj、main.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;
}执行相同的编译过程会导致链接错误
应答未解析的外部符号"public: static int C::
“
所以,为了回答你的问题。这是可能的。链接器并不关心哪个对象文件包含该值的定义(只要它只定义了一次)。然而,我不会推荐它。
https://stackoverflow.com/questions/29072624
复制相似问题