简体   繁体   中英

How does a class access a public method in another class in C++

I am new to C++, and confused about how does a class access a public method in another class in C++. For example,

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

And now I want the class B can access the public method "setDimension" in class A. I think the dependency files are included, but when I run the program, I got an error says that setDimension was not declared in this scope . How can I call the setDimension method inside class B. Many thanks!

You have first to create an instance of object A and then call setDimension on this instance.

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

Or you need to declare the method as static and can call it without instantiation:

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

If Class A is abstract:

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

You need to create an A (and choose a particular width and height, or pass those in from somewhere) so that you can use its method

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

You can declare the method setDimension(int width,int height); in class A as static.

static void setDimension(int width,int height);

void B::function(){

    A::setDimension()

}

You access static member functions using the class name and the scope resolution operator ::

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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