C++中#include用错的后果

今天做一个模块的时候遇到的这个问题。抽象一下,代码如下:

文件结构:

报错:

 

这个报错貌似说的是Box.h中的代码有问题。其实问题的根源在于Cup.h中多余的#include "Box.h"(因为Box.h有#include "Cup.h",所以就构成了循环导致出错!)

解决办法当然就是删掉那条多余的#include指令

感觉C++的编译器基本上报错如果遇到比较复杂的情况的时候,报错信息基本上没有什么参考价值,除了误导就是误导,所以,在写C++的时候一定要小心又小心啊!

 

代码:

Box.h

#ifndef BOX_H
#define BOX_H

#include "Cup.h"

class Box
{
    public:
        Box();
        ~Box();
};

Cup* getCup();

void deleteCup(Cup *p);

#endif // BOX_H

 

Box.cpp

#include "Box.h"

#include <iostream>

using namespace std;

Box::Box()
{
    cout << "Box cons" << endl;
}

Box::~Box()
{
    cout << "Box des" << endl;
}

Cup* getCup() {
    return new Cup();
}

void deleteCup(Cup *p) {
    delete p;
}

Cup.h

#ifndef CUP_H
#define CUP_H

#include "Box.h"

class Cup
{

    friend Cup* getCup();

    public:
        ~Cup();
    private:
        Cup();

};

#endif // CUP_H

 

Cup.cpp

#include "Cup.h"
#include <iostream>

using namespace std;

Cup::Cup()
{
    cout << "Cup cons" << endl;
}

Cup::~Cup()
{
    cout << "Cup des" << endl;
}

 

main.cpp

#include "Box.h"
#include "Cup.h"

int main() {
    Cup *p = getCup();
    Box box;
    deleteCup(p);
}

 

posted @ 2014-11-14 21:50  rldts  阅读(491)  评论(0编辑  收藏  举报