同班,不同大小......?

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* pATest* pB都具有成员变量m_Test [].

如果类的大小TestBho.cpp1,则PB为奇怪,不是吗?

我不明白发生了什么,请告诉我.提前致谢.

环境:Microsoft Visual Studio 2005 SP1(或SP2?)

Bil*_*eal 13

您的代码显示未定义的行为.您违反了一个定义规则(类Test在两个地方定义不同).因此,允许编译器做任何想做的事情,包括"怪异"的行为.


AnT*_*AnT 13

您违反了一个定义规则(ODR)的要求.程序的行为未定义.这是唯一正在发生的事情.

根据ODR,具有外部联系的类必须在所有翻译单元中以相同的方式定义.

  • @Let_Me_Be:我急切地等待你对同一类的不同定义在PIMPL中扮演的角色的解释.(定义的差异实际上是问题的关键). (3认同)