免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1719 | 回复: 2
打印 上一主题 下一主题

[C++] 关于头文件的问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-03-17 14:48 |只看该作者 |倒序浏览
不好意思要请教大家一个比较弱智的问题,希望大家不要介意,我google了好久也没找到答案。。。

在头文件t.h中定义了一个类

class MyClass
{
public:
           MyClass ();                     
           void p();
};

在t.cpp中的实现如下

#include "t.h"
#include <iostream>
MyClass::MyClass ()
{
}

void MyClass::p (  )
{
        std::cout<<2<<std::endl;
        return ;
}

在上面这种情况下,如果直接在t。cpp中写一个mian函数
如下
int main (int argc, char const* argv[])
{
        MyClass m;
        m.p();
                return 0;
}

程序编译以及运行都没有问题

但是,如果我在t。h中加多这几条宏命令
#ifndef TT
#define TT
#else

//这里是类的定义,如上

#endif

则会有如下的错误

t.cpp|34| error: ‘MyClass’ has not been declared
t.cpp|34| error: ISO C++ forbids declaration of ‘MyClass’ with no type
t.cpp|41| error: ‘MyClass’ is not a class or namespace
t.cpp|49| error: ‘MyClass’ is not a class or namespace
|| /home/snake/devel/test/t.cpp: In function ‘int main(int, const char**)’:
t.cpp|58| error: expected `;' before ‘m’
t.cpp|58| warning: statement is a reference, not call, to function ‘MyClass’
t.cpp|58| warning: statement has no effect
t.cpp|59| error: ‘m’ was not declared in this scope


另外,如果main函数不写在t。cpp文件中,而是写在另一个文件mian。cpp中,如下

#include "t.h"
int main (int argc, char const* argv[])
{
        MyClass m;
        m.p();
                return 0;
}

则不管t。h中是否有宏命令,都会有如下错误
main.cpp: In function ‘int main(int, const char**)’:
main.cpp:24: error: ‘MyClass’ was not declared in this scope
main.cpp:24: error: expected `;' before ‘m’
main.cpp:25: error: ‘m’ was not declared in this scope
t.cpp:34: error: ‘MyClass’ has not been declared
t.cpp:34: error: ISO C++ forbids declaration of ‘MyClass’ with no type
t.cpp:41: error: ‘MyClass’ is not a class or namespace
t.cpp:49: error: ‘MyClass’ is not a class or namespace
t.cpp: In function ‘int main(int, const char**)’:
t.cpp:58: error: expected `;' before ‘m’
t.cpp:59: error: ‘m’ was not declared in this scope



三个文件都在同一个目录中,请问为什么会出现这些错误,以及如何解决?

谢谢!

论坛徽章:
1
天蝎座
日期:2013-08-25 10:27:22
2 [报告]
发表于 2009-03-17 14:57 |只看该作者
#else

去掉

论坛徽章:
0
3 [报告]
发表于 2009-03-17 15:07 |只看该作者
原帖由 yangsf5 于 2009-3-17 14:57 发表
#else

去掉



谢谢 ,的确是这个的问题。
仔细想了一下,发现我理解错了那几条宏命令。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP