Multiple definition of constructor

2019-09-14 23:59发布

问题:

I have a very simple program that doesn't compile due to multiple definition error. It is here:

main.cpp

#include <iostream>
#include "read_p.h"

using namespace std;

int main()
{

    return 0;
}

read_p.cpp

#include "read_p.h"

using namespace std;

void read_p()
{
    /*
    some code here
    */
}

read_p.h

#ifndef READ_P_H
#define READ_P_H

#include "buildings.h"

void read_p();

#endif

buildings.h

#ifndef BUILDINGS_H
#define BUILDINGS_H

#include "flag.h"

using namespace std;

/*     
some class here    
*/

#endif

flag.h

#ifndef FLAG_H
#define FLAG_H

using namespace std;

class
    Test
{
  private:
  public:
    int test_var;
    Test(int);
};
Test::Test(int a)
{
    test_var = a;
}

#endif

The compiler gives me the error that the constructor Test::Test is defined multiple times. Unlike questions I find online, this error is not due to including the cpp-file instead of the h-file.

Question: Where does the multiple definition of the constructor occur? And is the proper way to circumvent the issue by making the constructur inline?

回答1:

Change

Test(int);

to

inline Test(int);

Even better, fix your class definition to define member functions inline, which makes them implicitly inline:

class Test
{
public:
    int test_var;
    Test(int a) : test_var(a) {}
};

Otherwise, as always, defining a function in a header means that it gets defined in every translation unit that includes that header, which leads to multiple definitions.



标签: c++ class