访问类对象

Accessing class object

本文关键字:对象 访问      更新时间:2023-10-16

我有三个.h和三个.cpp文件。

我在第一个 .h(比如 1.h(中创建了一个类的对象,该类位于 2.h 中。我想在我的 3.cpp 中使用该类对象。

1.小时

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;
}

它允许我毫无怨言地制作对象,但是,我的程序在运行时会出现此错误:

错误 C2065"对象":未声明的标识符

我不认为这是一个困难的问题,但我很难通过搜索栏解释我的问题。如果你能帮助我,我将不胜感激。

OnPressed()Three的成员,但Three不是从Two派生出来的,所以Three没有任何OnPressed()可以访问的object成员。 这就是编译器所抱怨的。

您需要:

  1. 使Three源于Two

    class Three : public Two
    
  2. 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;
    }