【发布时间】:2025-11-26 05:35:01
【问题描述】:
我有两个类 A 和 B,其中类 B 看起来像
B.h
class B
{
public:
B();
virtual ~B();
void eval(int a, int b);
private:
A* APointer;
};
相应地我有
B.cpp
B::B():APointer(NULL){}
B::~B(){}
void B::eval(int a, int b)
{
if a == b
{
APointer->run(); // run() is a public method defined in class A
}
}
那么A类就是这样的:
A.h
#include "LuaBridge.h"
extern "C" {
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}
using namespace luabridge;
class LuaParser
{
public:
LuaParser(lua_State* L);
virtual ~LuaParser();
void run();
private:
LuaRef mRun;
LuaRef mStop;
lua_State* mL;
};
还有
A.cpp
LuaParser::LuaParser(lua_State* L) :mRun(L),mStop(L),mL(L) {}
LuaParser::~LuaParser(){}
void LuaParser::run(){
std::cout<<"This project runs!"<<std::endl;
}
系统很复杂,实际上我在类C成员函数中调用了这个eval函数。在那个类中,我通过B* BPointer 定义了一个私有成员BPointer,在构造函数中我做了C(B* BPointer = NULL),然后我只是在类C 成员函数中使用BPointer->eval(a,b)。
在我的 main 代码中,我在 B 类中定义了一个指针,如 B* BPointer,我使用该指针调用方法 B::eval by
BPointer -> eval(a, b);
但是,当我在 Visual Studio 中逐步运行它时,在命令行APointer->run(); 我注意到this 指针类似于:
Value: 0xcdcdcdcd{APointer=???}
当我尝试运行此命令时,出现错误:
Access violation reading location 0xCDCDCDD1.
嗯...我不知道如何解决这个问题,我想知道的是:
整个想法(即在此类的方法中使用私有对象调用另一个类的函数)是否可行?
如果这个想法可行,那我应该如何修改我的代码呢?
欢迎提出任何建议或想法!
【问题讨论】:
-
请提供APointer和BPointer的初始化代码(如有)
-
您正在使用未初始化且无效的指针。为什么会有这么多指针?