zoukankan      html  css  js  c++  java
  • 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);
    }
  • 相关阅读:
    MYSQL转MSSQL
    SVN 服务器IP地址变更后客户端的修改
    gridview
    gridview外边距
    Android开发:自定义GridView/ListView数据源
    Android之Adapter用法总结
    collection set
    listview优化
    android应用开发全程实录-你有多熟悉listview
    android模块
  • 原文地址:https://www.cnblogs.com/qrlozte/p/4098259.html
Copyright © 2011-2022 走看看