C++, good old LNK1169 (and LNK2005) errors

前端 未结 3 968
暖寄归人
暖寄归人 2020-12-22 02:52

I have 4 files, 2 headers and 2 cpp files.

Header file one:

#ifndef complex_2
#define complex_2
#include
#include

using         


        
3条回答
  •  旧巷少年郎
    2020-12-22 03:27

    When you define a standalone function (with a body) in header file you must use inline (functions defined within class definition are inline by default).

    E.g. in header file one must be :

    inline ostream& operator<< (ostream &mm, const complex &c){
        if(c.get_im() >= 0){
            mm << "(" << c.get_re() << " + " << c.get_im() << "i)" << endl;
        }
        if(c.get_im() < 0){
            mm << "(" << c.get_re() << " - " << -(c.get_im()) << "i)" << endl;
        }
        return mm;
    }
    

    Otherwise you will define this function in each translation unit that includes that header and thus may get multiple definition error.

提交回复
热议问题