gpt4 book ai didi

c++无法通过指向该对象的指针将指针分配给该对象

转载 作者:行者123 更新时间:2023-11-28 06:55:54 25 4
gpt4 key购买 nike

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

在 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

最佳答案

您正在按值传递并使用这些值您正在创建临时拷贝并获取它们的地址,一旦超出范围,它们当然就会失效。

更改 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");`

关于c++无法通过指向该对象的指针将指针分配给该对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23177895/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com