构造函数的多重定义
Multiple definition of constructor
我有一个非常简单的程序,该程序由于多个定义错误而不会编译。它在这里:
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) {}
};
否则,与往常一样,在标题中定义功能意味着它在包含该标头的每个翻译单元中都定义,这会导致多个定义。
相关文章:
- 具有自定义构造函数 (C++) 的类型的动态数组分配
- 当类成员参数具有相同的名称时,如何定义构造函数?
- C++定义构造函数使对象成为非 POD
- 请描述一下在 c++ 中在此类中定义构造函数的方式?
- 不为 emplace() 定义构造函数的解决方法
- 已定义构造函数的构造函数无法识别
- 在自定义构造函数中的堆上创建指针
- c++ 17 中结构自动定义构造函数的规则是什么?
- Python 错误:在 SWIG 生成的C++模板化代码模块中没有定义构造函数
- unique_ptr看不到派生类的自定义构造函数
- 两种类型的定义构造函数有什么区别?第一个使用":",第二个用大括号(如函数)定义它
- 为什么一个非平凡的成员需要为同一类中的匿名联合定义构造函数
- 为其成员根据模板基类存在的类定义构造函数
- 如何在派生类上具有默认行为,而不是重新定义构造函数
- 在结构中定义构造函数
- 将从基类继承的构造函数与自定义构造函数混合使用
- 如何在模板类外部定义构造函数
- C 需要使用自定义构造函数的帮助
- 可以联合包含具有用户定义构造函数的类的对象
- 具有用户定义构造函数的非聚合类的值初始化