C++ 构造函数的多重定义
我有一个非常简单的程序,由于多定义错误而无法编译。在这里: main.cppC++ 构造函数的多重定义,c++,class,C++,Class,我有一个非常简单的程序,由于多定义错误而无法编译。在这里: main.cpp #include <iostream> #include "read_p.h" using namespace std; int main() { return 0; } #include "read_p.h" using namespace std; void read_p() { /* some code here */ } 阅读p.h #ifndef RE
#include <iostream>
#include "read_p.h"
using namespace std;
int main()
{
return 0;
}
#include "read_p.h"
using namespace std;
void read_p()
{
/*
some code here
*/
}
阅读p.h
#ifndef READ_P_H
#define READ_P_H
#include "buildings.h"
void read_p();
#endif
#ifndef BUILDINGS_H
#define BUILDINGS_H
#include "flag.h"
using namespace std;
/*
some class here
*/
#endif
#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
建筑物.h
#ifndef READ_P_H
#define READ_P_H
#include "buildings.h"
void read_p();
#endif
#ifndef BUILDINGS_H
#define BUILDINGS_H
#include "flag.h"
using namespace std;
/*
some class here
*/
#endif
#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
flag.h
#ifndef READ_P_H
#define READ_P_H
#include "buildings.h"
void read_p();
#endif
#ifndef BUILDINGS_H
#define BUILDINGS_H
#include "flag.h"
using namespace std;
/*
some class here
*/
#endif
#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文件
问题:构造函数的多重定义出现在哪里?通过使构造函数内联来规避这个问题的正确方法是什么 变化
Test(int);
到
更好的是,修改类定义以内联定义成员函数,这使它们隐式地内联
:
class Test
{
public:
int test_var;
Test(int a) : test_var(a) {}
};
否则,像往常一样,在头中定义函数意味着在包含该头的每个翻译单元中定义它,这将导致多个定义