构造函数的多个定义 [英] Multiple definition of constructor
问题描述
我有一个非常简单的程序,由于多重定义错误而无法编译。它在这里:
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
编译器给我错误构造函数 Test :: Test
被多次定义。与我在网上找到的问题不同,该错误不是由于包含cpp文件而不是h文件。
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
?
推荐答案
更改
Test(int);
到
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.
这篇关于构造函数的多个定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!