我有三个 .h 和三个 .cpp 文件。
我在 2.h 中的类中的第一个 .h(比如 1.h)中创建了一个类的对象。我想在我的 3.cpp 中使用该类对象。
1.h
class One
{
bool pressed;
...
}
2.h
#include "1.h"
Class Two
{
public:
One object;
...
}
3.h
#include "2.h"
Class Three
{ ...
}
3.cpp
#include "3.h"
void Three::OnPressed()
{
object.pressed = true;
}
它允许我毫无怨言地制作对象,但是,我的程序在运行时给出了这个错误:
error C2065 'object': 未声明的标识符
我认为这不是一个难题,但我在尝试通过搜索栏解释我的问题时遇到了麻烦。如果你能帮助我,我将不胜感激。
最佳答案
OnPressed()
是 Three
的成员,但是 Three
不源自 Two
, 所以 Three
没有任何 object
成员(member)那OnPressed()
可以访问。这就是编译器所提示的。
您需要:
制作
Three
派生自Two
class Three : public Two
给
Three
作为One
实例的成员(就像你对Two
所做的一样):class Three { public: One object; void OnPressed(); ... }; void Three::OnPressed() { object.pressed = true; }
或者给它一个
Two
的实例:class Three { public: Two object2; void OnPressed(); ... }; void Three::OnPressed() { object2.object.pressed = true; }
关于c++ - 访问类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45336417/