加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 同班,不同大小……?

发布时间:2020-12-16 06:49:16 所属栏目:百科 来源:网络整理
导读:看到代码,然后你会明白我的困惑. Test.h class Test {public:#ifndef HIDE_VARIABLE int m_Test[10];#endif}; Aho.h class Test;int GetSizeA();Test* GetNewTestA(); Aho.cpp //#define HIDE_VARIABLE#include "Test.h"#include "Aho.h"int GetSizeA() { re
看到代码,然后你会明白我的困惑.

Test.h

class Test {
public:
#ifndef HIDE_VARIABLE
    int m_Test[10];
#endif
};

Aho.h

class Test;

int GetSizeA();
Test* GetNewTestA();

Aho.cpp

//#define HIDE_VARIABLE
#include "Test.h"
#include "Aho.h"

int GetSizeA() { return sizeof(Test); }
Test* GetNewTestA() { return new Test(); }

Bho.h

class Test;

int GetSizeB();
Test* GetNewTestB();

Bho.cpp

#define HIDE_VARIABLE   // important!
#include "Test.h"
#include "Bho.h"

int GetSizeB() { return sizeof(Test); }
Test* GetNewTestB() { return new Test(); }

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;
}

Aho.cpp没有#define HIDE_VARIABLE,所以GetSizeA()返回40,但是
Bho.cpp执行#define HIDE_VARIABLE,因此GetSizeB()返回1.
但是,Test * pA和Test * pB都有成员变量m_Test [].

如果来自Bho.cpp的类Test的大小是1,那么pB很奇怪,不是吗?

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

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

解决方法

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读