2015-11-09 107 views
0

在下面的代码中,我认为结构stSameNameButDifferent是本地作用域定义,所以它没有问题。但是我在运行时遇到错误。 (错误:进程崩溃)C++ /范围结构

你能解释一下什么是错的代码?

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_a.cpp

#include <iostream> 
#include <sstream> 
#include <cstdint> 
#include <list> 
#include "test_function.h" 

struct stSameNameButDifferent 
{ 
     uint32_t nPlayCode; 
     uint32_t nGameID; 
     std::string sGameName; 
}; 

void test_a() 
{ 
     std::list<stSameNameButDifferent> lstSt; 
     for(int i=0; i<10; ++i) 
     { 
       stSameNameButDifferent st; 
       st.nPlayCode = i; 
       st.nGameID = 100+i; 
       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; 
     } 
} 

test_b.cpp

#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; 
     } 
} 
+2

恭喜,你见过你的第一个不平凡的大小的程序,现在你知道为什么你不应该使用'使用命名空间std;'和希望定义自己的命名空间。 – Surt

+1

_“我得到了错误”_有什么错误? –

+0

@Surt:这与'使用命名空间std'无关。 –

回答

2

间在多个翻译单位相同struct名为了避免发生冲突,你必须把它们放在一个未命名的命名空间中,像这样:

namespace { 
    struct stSameNameButDifferent { 
     uint32_t nPlayCode; 
     uint32_t nGameID; 
     std::string sGameName; 
    }; 
} 

这将使stSameNameButDifferent只在相应的翻译单元(.cpp文件)看到私人。

否则,链接器将会找到找到的第一个符号,因此会在运行时看到错误。

0

已在全球范围内定义stSameNameButDifferent,所以编译器看不到了两个定义分析以相同struct,而且只取第一个它满足,这就是为什么你得到一个错误。

对于test_atest_b,可以使用两个不同的命名空间,所以不会出现任何错误。

+0

_“编译器可以看到两个定义到相同的结构”_你错了。 –

+0

@LightnessRacesinOrbit,谢谢。修复。 – ANjaNA