Skip to content

Latest commit

 

History

History
154 lines (135 loc) · 2.75 KB

11.多文件编程.md

File metadata and controls

154 lines (135 loc) · 2.75 KB

如何防止头文件被重复引入

防止头文件被重复引入

  • 1) 使用宏定义避免重复引入
#ifndef _NAME_H
#define _NAME_H
//头文件内容
#endif
  • 2) 使用#pragma once避免重复引入 几乎所有常见的编译器都支持#pragma once 指令

  • 3) 使用_Pragma操作符 C99 标准中新增加了一个和 #pragma 指令类似的 _Pragma("once"),其可以看做是 #pragma 的增强版,不仅可以实现 #pragma 所有的功能,更重要的是,_Pragma 还能和宏搭配使用。

命名空间在多文件编程中的使用

//student_li.h
#ifndef _STUDENT_LI_H
#define _STUDENT_LI_H
namespace Li {  //小李的变量定义
    class Student {
    public:
        void display();
    };
}
#endif

//student_li.cpp
#include "student_li.h"
#include <iostream>
void Li::Student::display() {
    std::cout << "Li::display" << std::endl;
}

//student_han.h
#ifndef _STUDENT_HAN_H
#define _STUDENT_HAN_H
namespace Han {     //小韩的变量定义
    class Student {
    public:
        void display();
    };
}
#endif

//student_han.cpp
#include "student_han.h"
#include <iostream>
void Han::Student::display() {
    std::cout << "han::display" << std::endl;
}

//main.cpp
#include <iostream>
#include "student_han.h"
#include "student_li.h"
int main() {
    Li::Student stu1;
    stu1.display();
    Han::Student stu2;
    stu2.display();
    return 0;
}

带有命名空间的类的前置声明

SpaceA.h

#pragma once
namespace TestA {
    class SpaceA {
    public:
        SpaceA();
        ~SpaceA();

        void print();
    };
}

SpaceB.h

//在使用之前声明一下
namespace TestA {
    class SpaceA;
}

namespace TestB {
    class SpaceB {
    public:
        SpaceB();
        ~SpaceB();
        void printB();
    private:
        TestA::SpaceA* a;//使用的时候,必须加上命名空间
    };
}

C++ const常量如何在多文件编程中使用?

  1. 将const常量定义在.h头文件中
//demo.h
#ifndef _DEMO_H
#define _DEMO_H
const int num = 10;
#endif

//main.cpp
#include <iostream>
#include "demo.h"
int main() {
    std::cout << num << std::endl;
    return 0;
}
  1. 借助extern先声明再定义const常量
//demo.h
#ifndef _DEMO_H
#define _DEMO_H
extern const int num;  //声明 const 常量
#endif

//demo.cpp
#include "demo.h"   //一定要引入该头文件
const int num =10;  //定义 .h 文件中声明的 num 常量

//main.cpp
#include <iostream>
#include "demo.h"
int main() {
    std::cout << num << std::endl;
    return 0;
}
  1. 借助extern直接定义const常量
//demo.cpp
extern const int num =10;

//main.cpp
#include <iostream>
extern const int num;
int main() {
    std::cout << num << std::endl;
    return 0;
}