“多个定义"指的是“多个定义".错误? [英] "multiple definition" error?

查看:131
本文介绍了“多个定义"指的是“多个定义".错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我编译源代码"g ++ main.cpp Test.cpp"时,遇到错误:
"/tmp/ccSer90m.o:(.bss + 0x0):`Test :: count'的多个定义
/tmp/cc7iaBlq.o:(.bss + 0x0):首先在此处定义
collect2:ld返回1退出状态"

文件"Test.h":

when i compile my source code ""g++ main.cpp Test.cpp", i have met error:
"/tmp/ccSer90m.o: (.bss+0x0): multiple definition of `Test::count''
/tmp/cc7iaBlq.o: (.bss+0x0): first defined here
collect2: ld returned 1 exit status"

File "Test.h":

class Test
{
public:
        Test();
private:
        static int count;
};
int Test::count = 0;


文件"Test.cpp":


File "Test.cpp":

#include <stdio.h>
#include <stdlib.h>
#include "Test.h"
using namespace std;
Test::Test()
{
        count++;
        cout<<count<<endl;
}


文件"main.cpp"


File "main.cpp"

#include <stdio.h>
#include <stdlib.h>
#include "Test.h"
using namespace std;

int main ( int argc, char *argv[] )
{
        Test* t = new Test();
        return EXIT_SUCCESS;
}  





Please solve this error help me, thanks!

推荐答案

定义(int Test::count = 0;)必须放在.cpp文件中,而不能放在头文件中.
The definition (int Test::count = 0;) must be put in a .cpp file and not in a header file.

blockquote>


尝试移动此行:
Try moving this line:
int Test::count = 0;



从.h文件到.cpp文件.

问题在于,每次包含"Test.h"时,都会定义计数变量-因此有多个定义.将行移至.cpp文件可确保仅存在一个count定义.



from the .h file to the .cpp file.

The problem is that each time you include "Test.h" the count variable gets defined - hence multiple definitions. Moving the line to the .cpp file ensures that there is only one definition of count.


这篇关于“多个定义"指的是“多个定义".错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆