P-P*_*P-P 3 c++ visual-studio-2005 visual-c++
看到代码,然后你会明白我的困惑.
Test.h
class Test {
public:
#ifndef HIDE_VARIABLE
int m_Test[10];
#endif
};
Run Code Online (Sandbox Code Playgroud)
Aho.h
class Test;
int GetSizeA();
Test* GetNewTestA();
Run Code Online (Sandbox Code Playgroud)
Aho.cpp
//#define HIDE_VARIABLE
#include "Test.h"
#include "Aho.h"
int GetSizeA() { return sizeof(Test); }
Test* GetNewTestA() { return new Test(); }
Run Code Online (Sandbox Code Playgroud)
Bho.h
class Test;
int GetSizeB();
Test* GetNewTestB();
Run Code Online (Sandbox Code Playgroud)
Bho.cpp
#define HIDE_VARIABLE // important!
#include "Test.h"
#include "Bho.h"
int GetSizeB() { return sizeof(Test); }
Test* GetNewTestB() { return new Test(); }
Run Code Online (Sandbox Code Playgroud)
TestPrj.cpp
#include "Aho.h"
#include "Bho.h"
#include "Test.h"
int _tmain(int argc, _TCHAR* argv[]) {
int a = GetSizeA();
int b = GetSizeB();
Test* pA = GetNewTestA();
Test* pB = GetNewTestB();
pA->m_Test[0] = 1;
pB->m_Test[0] = 1;
// output : 40 1
std::cout << a << '\t' << b << std::endl;
char temp;
std::cin >> temp;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Aho.cpp不#define HIDE_VARIABLE
,所以GetSizeA()
返回40,但Bho.cpp确实#define HIDE_VARIABLE
,所以GetSizeB()
返回1.但是,Test* pA
并Test* pB
都具有成员变量m_Test [].
如果类的大小Test
从Bho.cpp
1,则PB为奇怪,不是吗?
我不明白发生了什么,请告诉我.提前致谢.
环境:Microsoft Visual Studio 2005 SP1(或SP2?)
AnT*_*AnT 13
您违反了一个定义规则(ODR)的要求.程序的行为未定义.这是唯一正在发生的事情.
根据ODR,具有外部联系的类必须在所有翻译单元中以相同的方式定义.
归档时间: |
|
查看次数: |
329 次 |
最近记录: |