C++ c++;/结构范围
在下面的代码中,我认为结构stSameNameButtoDifferent是本地范围定义,所以它没有问题。但我在运行时出错了。 (错误:进程崩溃) 你能解释一下那个代码有什么问题吗 test_function.hC++ c++;/结构范围,c++,scope,C++,Scope,在下面的代码中,我认为结构stSameNameButtoDifferent是本地范围定义,所以它没有问题。但我在运行时出错了。 (错误:进程崩溃) 你能解释一下那个代码有什么问题吗 test_function.h #ifndef TEST_FUNC_H_ #define TEST_FUNC_H_ void test_a(); void test_b(); #endif main.cpp #include <iostream> #include "test_function.h"
#ifndef TEST_FUNC_H_
#define TEST_FUNC_H_
void test_a();
void test_b();
#endif
main.cpp
#include <iostream>
#include "test_function.h"
using namespace std;
int main(int argc, const char** argv)
{
cout << "testing for struct scope" << endl;
test_a();
test_b();
return 0;
}
#包括
#包括“test_function.h”
使用名称空间std;
int main(int argc,常量字符**argv)
{
cout为了避免相同的结构
名称在多个翻译单元中发生冲突,您必须将它们放在一个未命名的名称空间中,如下所示:
namespace {
struct stSameNameButDifferent {
uint32_t nPlayCode;
uint32_t nGameID;
std::string sGameName;
};
}
这将使stsamenabebutdifferent
仅在相应的翻译单元(.cpp
文件)中私自可见
否则,链接器将使用找到的第一个符号解析符号,从而解析运行时看到的错误。您已在全局范围内定义了stsamenabuttodifferent
,因此编译器无法查看和分析同一结构的两个定义,它只使用它遇到的第一个,这就是为什么会出现错误。
您可以为test\u a
和test\u b
使用两个不同的名称空间,这样您就不会出现任何错误。祝贺您,您已经遇到了第一个非普通大小的程序,现在您知道了为什么不应该使用使用名称空间std;
并希望定义您自己的名称空间。“我有错误”什么错误?!@Surt:这与使用命名空间std的无关@LightnessRacesinOrbit,进程崩溃了。@heon:调试器说是什么原因造成的?“我出错了”和“进程崩溃了”都不是完整的问题描述。它们甚至不是完整的句子。来吧…“编译器可以看到同一结构的两个定义”你错了。
#include <iostream>
#include <sstream>
#include <cstdint>
#include <list>
#include "test_function.h"
struct stSameNameButDifferent
{
uint32_t nPlayCode;
uint32_t nGameID;
float fDiscountRate;
std::string sGameName;
};
void test_b()
{
std::list<stSameNameButDifferent> lstSt;
for(int i=0; i<10; ++i)
{
stSameNameButDifferent st;
st.nPlayCode = i;
st.nGameID = 1000+i;
st.fDiscountRate = (float)i/100;
std::ostringstream osBuf;
osBuf << "Game_" << i;
st.sGameName = osBuf.str();
lstSt.push_back(st);
}
for(auto &st : lstSt)
{
std::cout << st.nPlayCode << ", " << st.nGameID << ", " << st.sGameName << std::endl;
}
}
namespace {
struct stSameNameButDifferent {
uint32_t nPlayCode;
uint32_t nGameID;
std::string sGameName;
};
}