简体   繁体   中英

Call a member function of other Class

I have 2 classes.

Class A
{
  void printMe();
}

cpp File:

A::printMe(){
   cout<<"yay";
 }

Class B
 {
    void DoSomething();
 }

cpp File

 B::DoSomething(){

    A::printMe();
 }

How do I make an object of Class A in Class B and use it for the function printMe();

References, but the answers are not accepted and they did not work for me HERE

Assuming you want to call the printMe() member function on an object of class A:

B::DoSomething() {
  A a;
  a.printMe();
}

However you also need to declare the printMe() function to be public:

class A {
public:
  void printeMe();
}

First you'll need to correct the many syntax errors:

// A.h
class A {    // not Class
public:      // otherwise you can only call the function from A
    void printMe();
};           // missing ;

// B.h
class B {    // not Class
public:      // probably needed
    void DoSomething();
};           // missing ;

// A.cpp
#include "A.h"       // class definition is needed
#include <iostream>  // I/O library is needed (cout)

void A::printMe() {        // missing return type
    std::cout << "yay\n";  // missing namespace qualifier
}

// B.cpp
#include "A.h"       // class definitions are needed
#include "B.h"

void B::DoSomething() {    // missing return type
    A a;                   // make an object of type A
    a.printMe();           // call member function
}

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