将值分配给结构字段时,程序崩溃

时间:2014-12-28 08:22:57

标签: c++ visual-c++

我正在学习C ++,最近我遇到了一个问题,不知道为什么。

我想隐藏外部用户的私有成员字段详细信息,所以我只是 声明一个void *指针作为唯一一个私有成员字段,然后声明 类'.cpp源文件中的真实成员字段结构。新的这个内心隐藏 类构造函数中的结构,并在类析构函数中删除它。

以下是我的测试代码:

ItemA.h

#pragma once

class ItemA
{
private:
    void* pFields;

public:
    ItemA();
    ~ItemA();
};

ItemA.cpp

#include "ItemA.h"
#include <string>

using namespace std;

typedef struct
{
    int    intField;
    string strField;
} HFIELDS, *PHFIELDS;

ItemA::ItemA()
{
    this->pFields = new HFIELDS;
    PHFIELDS pHFIELDS = (PHFIELDS)this->pFields;
    pHFIELDS->intField = 100;
    pHFIELDS->strField = "100";
}

ItemA::~ItemA()
{
    PHFIELDS pHFIELDS = (PHFIELDS)this->pFields;
    delete pHFIELDS;
}

ItemB.h

#pragma once

#include "ItemA.h"

class ItemB
{
private:
    void* pFields;
    ItemB();

public:
    ItemB(ItemA &itemA);
    ~ItemB();
};

ItemB.cpp

#include "ItemB.h"
#include <string>

using namespace std;

typedef struct
{
    ItemA* pItemA;
    int    intField;
    string strField;
} HFIELDS, *PHFIELDS;

ItemB::ItemB(ItemA &itemA)
{
    this->pFields = new HFIELDS;
    PHFIELDS pHFIELDS = (PHFIELDS)(this->pFields);
    pHFIELDS->pItemA = &itemA;
    pHFIELDS->intField = 200;
    pHFIELDS->strField = "200";
}


ItemB::~ItemB()
{
    PHFIELDS pHFIELDS = (PHFIELDS)this->pFields;
    delete pHFIELDS;
}

的main.cpp

#include <tchar.h>
#include "ItemA.h"
#include "ItemB.h"

int _tmain(int argc, _TCHAR* argv[])
{
    ItemA* pItemA = new ItemA();
    ItemB* pItemB = new ItemB(*pItemA);
    delete pItemB;
    delete pItemA;

    return 0;
}

当程序执行运行到ItemB的构造函数时,它崩溃了:

  

pHFIELDS-> strField =“200”;

有人可以告诉我它有什么问题吗?谢谢。

P.S。我使用的开发环境是MSVC2013。

1 个答案:

答案 0 :(得分:3)

为什么你有2个HFIELDS声明和* PHFIELDS

1)在ItemA.cpp

typedef struct
{
    int    intField;
    string strField;
} HFIELDS, *PHFIELDS;

2)在ItemB.cpp

typedef struct
{
    ItemA* pItemA;
    int    intField;
    string strField;
} HFIELDS, *PHFIELDS;

会发生什么,ItemA.h包含在ItemB中,因此编译器会看到2个声明。

请更改名称并编译。

希望这有帮助。