Error with multiple definitions of function

后端 未结 3 1784
感动是毒
感动是毒 2020-11-27 02:56

I am trying to relearn C++ after taking an intro course a few years ago and I’m having some basic problems. My current problem occurs when trying to use a friend function. H

3条回答
  •  星月不相逢
    2020-11-27 03:21

    The problem is that if you include fun.cpp in two places in your program, you will end up defining it twice, which isn't valid.

    You don't want to include cpp files. You want to include header files.

    The header file should just have the class definition. The corresponding cpp file, which you will compile separately, will have the function definition.

    fun.hpp:

    #include 
    
    class classA {
        friend void funct();
    public:
        classA(int a=1,int b=2):propa(a),propb(b){std::cout<<"constructor\n";}
    private:
        int propa;
        int propb;
        void outfun(){
            std::cout<<"propa="<

    fun.cpp:

    #include "fun.hpp"
    
    using namespace std;
    
    void funct(){
        cout<<"enter funct"<

    mainfile.cpp:

    #include 
    #include "fun.hpp"
    using namespace std;
    
    int main(int nargin,char* varargin[]) {
        cout<<"call funct"<

    Note that it is generally recommended to avoid using namespace std in header files.

提交回复
热议问题