构造函数的多重定义

Multiple definition of constructor

本文关键字:定义 构造函数      更新时间:2023-10-16

我有一个非常简单的程序,该程序由于多个定义错误而不会编译。它在这里:

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

编译器给我一个错误,即构造函数Test::Test被多次定义。与我在线发现的问题不同,此错误不是由于包括CPP文件而不是H文件。

问题:构造函数的多个定义在哪里发生?通过制造构造inline来避免问题的正确方法吗?

更改

Test(int);

to

inline Test(int);

更好的是,修复您的类定义以定义成员函数内联,这使它们隐含地 inline

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

否则,与往常一样,在标题中定义功能意味着它在包含该标头的每个翻译单元中都定义,这会导致多个定义。