C++的头文件中类声明后忘记加分号产生不可预期的编译错误

头文件 Test.h 的内容是
class Test
{
public:
 virtual void test1();   
}
实现文件是 Test.cpp
#include "Test.h"
#include <iostream>
using namespace std;
void Test::test1(){  cout<<"Hello"<<endl; }

编译时出现错误
c:\program files\microsoft visual studio\vc98\include\errno.h(29) : error C2143: syntax error : missing ';' before 'string'
c:\program files\microsoft visual studio\vc98\include\errno.h(29) : fatal error C1004: unexpected end of file found

不把这两个文件连接起来考虑是很难知道是那里错了,况且Unmi原来又是写java比C++多得多,java可没有#include的用法,其实有C++经验的人,明白了#include只是把被包含文件的内容引入到当前位置。
上面把Test.h的内容插入到Test.cpp文件中#include "Test.h"处,那就要注意了,类声明后必须要加上一个分号,可以把类声明当成是普通的变量声明语句一样,需要一分号结束,不然会出现许多不可预知的编译错误

错误类型并非就是只出现上面那样,主要看头文件内容引入到当前位置后,与随后语句差一个分号会出现什么语法错误,所以应该养成类声明后加分好的习惯就不会错的。

比如实现文件写成
#include "Test.h"
void Test::test1(){}

出现的错误就是

#include "Test.h"
void Test::test1(){}
C:\Documents and Settings\yanbin\My Documents\Visual Studio Projects\TestVirtual\Test.cpp(3) : error C2628: 'Test' followed by 'void' is illegal (did you forget a ';'?)
C:\Documents and Settings\yanbin\My Documents\Visual Studio Projects\TestVirtual\Test.cpp(3) : error C2556: 'class Test __thiscall Test::test1(void)' : overloaded function differs only by return type from 'void __thiscall Test::test1(void)'
        c:\documents and settings\yanbin\my documents\visual studio projects\testvirtual\test.h(4) : see declaration of 'test1'
C:\Documents and Settings\yanbin\My Documents\Visual Studio Projects\TestVirtual\Test.cpp(3) : error C2371: 'test1' : redefinition; different basic types
        c:\documents and settings\yanbin\my documents\visual studio projects\testvirtual\test.h(4) : see declaration of 'test1'

因为编译器看到了头文件的类声明与语句 void Test::test1(){} 之间没有分号。

类别: C++/VB. 标签: . 阅读(190). 订阅评论. TrackBack.

Leave a Reply

Be the First to Comment!

avatar