一杯清酒邀明月
天下本无事,庸人扰之而烦耳。
posts - 3121,comments - 209,views - 578万

这里我有三个源文件:Base.hpp, Base.cpp 和 main.cpp

在Base.hpp里面定义一个基类,注意,基类只包含构造函数和析构函数的声明,函数在Base.cpp里实现。

此外在Base.hpp中还有一个函数的定义(函数声明和定义都在Base.hpp文件中)三个文件代码如下:

复制代码
 1 // Base.hpp
 2 #ifndef BASE_HPP
 3 #define BASE_HPP
 4  
 5 #include<iostream>
 6 #include<string>
 7  
 8 using namespace std;
 9  
10 class Base{
11 public:
12     Base();
13  
14     ~Base();
15  
16 private:
17     char *p;
18 };
19  
20 void platform(Base *pBase){
21     cout << "this is just a function..." << endl;
22 }
23  
24 #endif
复制代码
复制代码
 1 //Base.cpp
 2 #include"Base.hpp"
 3  
 4 Base::Base(){
 5     cout << "construction function..." << endl;
 6 }
 7  
 8 Base::~Base(){
 9     cout << "destructor function..." << endl;
10     delete p;
11 }
12 /wanzew/article/details/81638128
复制代码
复制代码
 1 //main.cpp
 2 #include"Base.hpp"
 3 #include<iostream>
 4 using namespace std;
 5  
 6 int main(){
 7     cout << "main..." << endl;
 8  
 9     Base * pBase = new Base;
10     delete pBase;
11  
12     system("pause");
13     return 0;
14 }
复制代码

此时编译会出现一个问题:

1>Base.obj : error LNK2005: "void __cdecl platform(class Base *)" (?platform@@YAXPAVBase@@@Z) 已经在 main.obj 中定义
1>c:\users\wanzew\documents\visual studio 2013\Projects\Class\Debug\Class.exe : fatal error LNK1169: 找到一个或多个多重定义的符号

经过分析,确定了这是由于两个实现文件(main.cpp 和 base.cpp)中重复包含了头文件而造成的。
要注意的是,在这里,在头文件中加入#ifndef……#endif这样的预编译命令是没用的,因为这是防止嵌套包含头文件的,而本例中并没有嵌套包含,是 在两个文件中分别包含。

  • 解决方法:

只在头文件中声明函数,把函数定义都放到cpp文件中,本例中把platform函数的定义从Base.hpp文件中移到Base.cpp文件中。

把函数体放到cpp文件中后确实可行:

同理:如果在头文件中再定义一个变量:int a = 10; 那么由于头文件在两个cpp文件中都有被包含,也会出现类似的错误。

  • 解决方法

把变量的定义放到Base.cpp文件中。

posted on   一杯清酒邀明月  阅读(1727)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
· 全程使用 AI 从 0 到 1 写了个小工具
· 从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示