Access member function of another .cpp within same

2020-02-28 05:15发布

问题:

I am working in Visual C++. I have two .cpp files in the same source file. How can I access another class (.cpp) function in this main .cpp?

回答1:

You should define your class in a .h file, and implement it in a .cpp file. Then, include your .h file wherever you want to use your class.

For example

file use_me.h

#include <iostream>
class Use_me{

   public: void echo(char c);

};

file use_me.cpp

#include "use_me.h" //use_me.h must be placed in the same directory as use_me.cpp

void Use_me::echo(char c){std::cout<<c<<std::endl;}

main.cpp

#include "use_me.h"//use_me.h must be in the same directory as main.cpp
    int main(){
       char c = 1;

       Use_me use;
       use.echo(c);

       return 0;

    }


回答2:

Without creating header files. Use extern modifier.

a.cpp

extern int sum (int a, int b);

int main()
{
    int z = sum (2, 3);
    return 0;
}

b.cpp

int sum(int a, int b)
{
    return a + b;
}


回答3:

You should put the function declarations in an .hpp flie, and then #include it in the main.cpp file.

For instance, if the function you're calling is:

int foo(int bar)
{
   return bar/2;
}

you need to create a foobar.hpp file with this:

int foo(int bar);

and add the following to all .cpp files that call foo:

#include "foobar.hpp"


标签: c++ class