zoukankan      html  css  js  c++  java
  • 前置声明

    关于C++前置声明

    举下面一个例子:

    //a.h文件

    #pragma once
    #include "b.h"
    #include <iostream>
    using namespace std;
    class A
    {
    public:
    B *b1;

    void func1()
    {
    cout << "nihao shijie" << endl;
    }
    };

    //b.h文件

    #pragma once
    #include "a.h"
    #include <iostream>
    using namespace std;
    class B
    {
    public:
    A *a1;

    void func2()
    {
    cout << "Hello World" << endl;
    }
    };

    //main.cpp  ,调用

    #define _CRT_SECURE_NO_WARNING
    #include <iostream> 
    #include "a.h"
    #include "b.h"
    using namespace std;

    //函数入口
    int main()
    {
    A a;
    B b;
    a.func1();
    b.func2();
    system("pause"); //阻塞功能

    return EXIT_SUCCESS;
    }

     这时会报出:

    error C3646: “a1”: 未知重写说明符

    error C4430: 缺少类型说明符 - 假定为 int。注意: C++ 不支持默认 int

    这时因为文件分别编译,当编译完一个文件后,再另一个文件又重新调用了这个文件。这样会造成循环调用的。编译器为了避免这一情况。就直接帮我们报错了。

    那怎么解决这个问题呢。这时候就需要前置声明了。就是在编译时,告诉编译器,一会会有文件会重新调用。

    //a.h文件

    #pragma once
    #include "b.h"
    #include <iostream>
    using namespace std;
    class A
    {
    public:
    B *b1;

    void func1()
    {
    cout << "nihao shijie" << endl;
    }
    };

    //b.h文件

    #pragma once
    #include "a.h"
    #include <iostream>
    using namespace std;

    class A;
    class B
    {
    public:
    A *a1;

    void func2()
    {
    cout << "Hello World" << endl;
    }
    };

  • 相关阅读:
    字符编码乱码处理
    字典,元组,集合的使用
    三级菜单 ,求1
    运算符 if和while的使用
    if条件判断和while循环
    基本数据类型的结构和使用方法
    计算机基础部分
    计算机基础
    数据库之表查询,单表、多表,子查询
    google map API 学习
  • 原文地址:https://www.cnblogs.com/qq376142178/p/12395577.html
Copyright © 2011-2022 走看看