我有一个非常简单的程序,由于多个定义错误而无法编译.是这里:
main.cpp中
#include <iostream>
#include "read_p.h"
using namespace std;
int main()
{
return 0;
}
Run Code Online (Sandbox Code Playgroud)
read_p.cpp
#include "read_p.h"
using namespace std;
void read_p()
{
/*
some code here
*/
}
Run Code Online (Sandbox Code Playgroud)
read_p.h
#ifndef READ_P_H
#define READ_P_H
#include "buildings.h"
void read_p();
#endif
Run Code Online (Sandbox Code Playgroud)
buildings.h
#ifndef BUILDINGS_H
#define BUILDINGS_H
#include "flag.h"
using namespace std;
/*
some class here
*/
#endif
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
编译器给出了构造Test::Test函数多次定义的错误.与我在网上找到的问题不同,此错误不是由于包含cpp文件而不是h文件.
问题:构造函数的多重定义在哪里出现?是通过制作构造来规避问题的正确方法inline吗?
更改
Test(int);
Run Code Online (Sandbox Code Playgroud)
至
inline Test(int);
Run Code Online (Sandbox Code Playgroud)
更好的是,修复类定义以定义内联的成员函数,这使它们隐式inline:
class Test
{
public:
int test_var;
Test(int a) : test_var(a) {}
};
Run Code Online (Sandbox Code Playgroud)
否则,与往常一样,在标题中定义函数意味着它在包含该标题的每个翻译单元中定义,这导致多个定义.