C++中一个类如何访问另一个类中的公共方法

Xiu*_* Xu 1 c++

我是 C++ 新手,对 C++ 中一个类如何访问另一个类中的公共方法感到困惑。例如,

//.h of class A
class A {
public:
  void setDimension (int width, int height);
  A* obj;
}

//.cpp of class A
#include "A.h"
void A::setDimension (int width, int height) {
    // do some stuffs here
}

//.h of class B
#include "A.h"
class B {
public:
    void function ();
   //do something here
}

//.cpp of class B
#include "A.h"
#include "B.h"
void B::function() {
     obj->setDimension(int width, int height);
}
Run Code Online (Sandbox Code Playgroud)

现在我希望 B 类可以访问 A 类中的公共方法“setDimension”。我认为依赖文件已包含在内,但是当我运行程序时,我收到一条错误消息setDimension was not declared in this scope。我如何调用B类中的setDimension方法。非常感谢!

Cas*_*ius 5

您必须首先创建对象 A 的实例,然后在此实例上调用 setDimension。

 //.cpp of class B
#include "A.h"
#include "B.h"
void B::function() {
      A myInstance;
      myInstance.setDimension(10, 10);
}
Run Code Online (Sandbox Code Playgroud)

或者您需要将该方法声明为静态并且可以在不实例化的情况下调用它:

//.h of class A
class A {
   public:
     static void setDimension (int width, int height);
}

 //.cpp of class B
#include "A.h"
#include "B.h"
void B::function() {
     A::setDimension(10, 10);
}
Run Code Online (Sandbox Code Playgroud)

如果 A 类是抽象类:

//.h of class B
#include "A.h"
class B : A {
public:
    void function ();
}

//.cpp of class B
#include "A.h"
#include "B.h"
void B::function() {
     this->setDimension(10, 10);
}
Run Code Online (Sandbox Code Playgroud)