我是否正确使用头文件?

时间:2019-07-13 05:50:35

标签: c++ header-files

我想学习C ++中的头文件,所以我实现了简单的算法,并且想知道这是否是正确的方法。谢谢!

my_math.h

#pragma once

namespace math {    
    /**
     * returns the sum of numbers a and b
     * @param a the first number
     * @param b the second number
     * @return sum a + b
     */
    double sum(double a, double b);

    /**
     * returns the difference of numbers a and b
     * @param a the first number
     * @param b the second number
     * @return difference a - b
     */
    double difference(double a, double b);

    /**
     * returns the product of numbers a and b
     * @param a the first number
     * @param b the second number
     * @return product a * b
     */
    double product(double a, double b);

     /**
     * returns the dividen of numbers a and b
     * @param a the first number
     * @param b the second number
     * @return dividen a / b
     */
    double divide(double a, double b);
}

my_math.cpp


#include "my_math.h"

namespace math {
double sum(double a, double b) { return a + b; }
double difference(double a, double b) { return a - b; }
double product(double a, double b) { return a * b; }
double divide(double a, double b) { return a / b; }
}

main.cpp


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

using namespace std;
using namespace math;

int main() {
    cout << sum(4, 6) << endl;
    cout << difference(4, 6) << endl;
    cout << product(4, 6) << endl;
    cout << divide(24, 6) << endl;
}

我应该放

 namespace math { 
源文件和头文件中的

?在头文件中实现没有类的函数也是一种好习惯吗?

1 个答案:

答案 0 :(得分:3)

  

我应该放吗

namespace math { 
     

同时在源文件和头文件中?

实现my_math.h中声明的函数之一时,必须向编译器指示该函数位于math名称空间中。有两种方法可以做到:

方法1

完成后。

方法2

在每个函数实现中使用math::范围。

#include "my_math.h"

double math::sum(double a, double b) { return a + b; }
double math::difference(double a, double b) { return a - b; }
double math::product(double a, double b) { return a * b; }
double math::divide(double a, double b) { return a / b; }

就编译器而言,这两种方法完全相同。您可以使用任何一种方法。您甚至可以将两者混合使用。没问题。

  

在头文件中实现没有类的函数也是一种好习惯吗?

这个问题的答案很广泛。这不是解决它的最佳位置。