我是否正确使用了头文件

Am I using header files correctly?

本文关键字:文件 是否      更新时间:2023-10-16

我想了解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; }
}

主.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 { 

在源文件和头文件中?另外,在头文件中实现没有类的函数是好的约定吗?

我应该把

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; }

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

另外,在头文件中实现没有类的函数是好的约定吗?

这个问题的回答相当广泛。这不是解决它的最佳位置。