zoukankan      html  css  js  c++  java
  • c++ 头文件重复问题

    感谢:https://blog.csdn.net/u010757264/article/details/50075343

      在C++程序设计过程中,一般将类的声明、类的定义分开, 将类的声明放在.h的头文件中, 将类的定义放在.cpp的源文件中,这样使得程序设计模块分明。

      但是往往会出现典型问题:重复定义问题。如果一个类派生出一个类,派生类声明时需要包含基类的头文件,如果再在主函数包含这个头文件, 编译时就报错, 编译器出现重复定义的问题, 给出重定义错误提示。

    例子:首先在新建工程下新建两个.h的头文件(文件名分别为people.h和student.h),继续新建三个.cpp的源文件(文件名分别是people.cpp、student.cpp、main.cpp),然后编辑相应代码。

    // people.h头文件

    #include<iostream>

    using namespace std;

    class people{

    public:

    void breath();

    };

    // student.h 头文件    // 定义一个类student,从类people继承得到,重写成员函数breath()

    #include "people.h"

    #include<iostream>

    using namespace std;

    class student:public people{

    public:

    void breath();

    }

    // people.cpp源文件    // 定义类people的breath()方法

    #include "people.h"

    void people:breath(){

    cout <<"people" << endl;

    }

    // student.cpp源文件    // 重写类student的breath()方法

    #include "student.h"

    void student:breath(){

    cout << "student" << endl;

    }

    // main.cpp 源文件

    #include "pepple.h"

    #include "student.h"

    int main(){

      people p;

      student s;

      p.breath();

      s.breath();

      return 0;

    }

      对三个cpp进行编译,对于people.cpp和student.cpp编译时,没有错误,但是对main.cpp进行编译时会出现类重复定义错误。因为"people.h"被定义了两次,编译器会报错。

      对于轻量程序,通过将所有代码写在一个源文件中,包括类的声明和定义,还有主函数,这样不用写#include "people.h"和#include "student.h"。但是对于大程序,这种方式不好,因为不仅会让代码显得冗长而且代码逻辑没有条理。

      因此,对于这种情况,最常用的方法是用条件编译#ifndef...#define...#endif语句。修改上面people.h和student.h文件。

  • 相关阅读:
    SpringMVC拦截器使用
    JavaCORBA
    Mybatis各语句高级用法(未完待续)
    [译文]C# Heap(ing) Vs Stack(ing) in .NET: Part II
    [译文]C# Heap(ing) Vs Stack(ing) in .NET: Part I
    iBatis连接MySQL时的注意事项
    MyBatis入门
    属性(property) VS 数据成员(field)
    [译文]C# Heap(ing) Vs Stack(ing) in .NET: Part III
    LINQ To Objects
  • 原文地址:https://www.cnblogs.com/jianfeifeng/p/11207076.html
Copyright © 2011-2022 走看看