c ++通过指向该对象的指针分配指向对象的指针

时间:2014-04-20 02:49:47

标签: c++ oop pointers

我无法通过将指针分配给指向该对象的另一个指针来分配指向对象的指针。这是我的代码:

在Map.h中:

using namespace std;
class Map;
Map *CurrentMap;
class Map
{
    private:
        Map *NM, *EM, *SM, *WM;
        string NMe, EMe, SMe, WMe;
    public:
        void Initialize(Map N, Map E, Map S, Map W, string MeN, string MeE, string MeS, string MeW)
        {
            NM = &N; EM = &E; SM = &S; WM = &W;
            NMe = MeN; EMe = MeE; SMe = MeS; WMe = MeW;
        }

        void GoNorth()
        {
            cout << NMe << endl;
            CurrentMap = NM;  //This is the problem, this is where it crashes my program
        }

        void GoEast()
        {
            cout << EMe << endl;
            CurrentMap = EM;
        }

        void GoSouth()
        {
            cout << SMe << endl;
            CurrentMap = SM;
        }

        void GoWest()
        {
            cout << WMe << endl;
            CurrentMap = WM;
        }
};

在Main.cpp中:

#include <iostream>
#include <string>
#include "Map.h"
using namespace std;

int main()
{
    Map A,B,C,D,E,F;
    A.Initialize(B,C,D,E,"Towards B","Towards C","Towards D","Towards E");
    B.Initialize(D,F,A,F,"Towards D","Towards F","Towards A","Towards F");
    C.Initialize(F,E,F,A,"Towards F","Towards E","Towards F","Towards A");
    D.Initialize(A,F,B,F,"Towards A","Towards F","Towards B","Towards F");
    E.Initialize(F,A,F,C,"Towards F","Towards A","Towards F","Towards C");
    F.Initialize(A,A,A,A,"Towards A","Towards A","Towards A","Towards A");
    CurrentMap = &A;

    CurrentMap->GoNorth();
    CurrentMap->GoNorth();
    CurrentMap->GoNorth();
    system("pause");
    return 0;
}

上述代码的预期输出为:

    Towards B
    Towards D
    Towards A

但我得到的是:

    Towards B
    //Crash, Unhandled Exception: Access violation reading location 0xcccccccc 

2 个答案:

答案 0 :(得分:1)

您正在通过值和这些值传递 你正在创建临时副本并获取它们的地址, 当它们超出范围时,它们当然会无效。

更改Initialize的签名以获取指针或引用。

`void Initialize(Map *N, Map *E, Map *S, Map *W, string MeN, string MeE, string MeS, string MeW);`

初始化时记下地址。

`A.Initialize(&B, &C, &D, &E,"Towards B","Towards C","Towards D","Towards E");`

答案 1 :(得分:0)

在下面的代码中,您将指向指向值传递的参数,这意味着只要Initialize()返回,您的类的指针现在指向不再存在的对象。

    void Initialize(Map N, Map E, Map S, Map W, string MeN, string MeE, string MeS, string MeW)
    {
        NM = &N; EM = &E; SM = &S; WM = &W;
        NMe = MeN; EMe = MeE; SMe = MeS; WMe = MeW;
    }

如果你真的希望你的类保存指向你在main()中声明的对象的指针,你需要改为通过引用:

    void Initialize(Map & N, Map & E, Map & S, Map & W, string MeN, string MeE, string MeS, string MeW)
    {
        NM = &N; EM = &E; SM = &S; WM = &W;
        NMe = MeN; EMe = MeE; SMe = MeS; WMe = MeW;
    }

...或者您可以更改Initialize()以接受指针参数(例如Map *)。但您可能想重新考虑您的设计,只需保存对象的副本,而不是指向其他地方声明的对象的指针。这样做会不那么脆弱,所以你不太可能犯错,导致你的程序崩溃。