繁体   English   中英

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

[英]How does a class access a public method in another class in 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);
}

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

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

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

或者,您需要将方法声明为静态方法,并且可以不实例化地调用它:

//.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);
}

如果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);
}

您需要创建一个A (并选择特定的宽度和高度,或从某个地方传递这些宽度和高度),以便可以使用其方法

void B::function() {
   A mya;
   int mywidth = 10;
   int myheight = 20;
   mya.setDimension(mywidth, myheight);
}

您可以声明方法setDimension(int width,int height); 在A类中为静态。

static void setDimension(int width,int height);

void B::function(){

    A::setDimension()

}

您可以使用类名称和范围解析运算符::访问静态成员函数::

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM