我是否正确使用了头文件
Am I using header files correctly?
我想了解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; }
就编译器而言,这两种方法完全相同。您可以使用其中任一方法。您甚至可以将两者混合使用。这没有错。
另外,在头文件中实现没有类的函数是好的约定吗?
这个问题的回答相当广泛。这不是解决它的最佳位置。
相关文章:
- 在C++中使用没有合作伙伴Class/Cpp文件的头文件是否实用
- 在头文件上包含 cpp 文件是否有缺点?
- 如何检查文件是否已存在于 fstream C++中
- 预处理的 C/C++ 文件是否特定于计算机?
- 如何使用 jpeglib.h 获取文件是否为 JPEG 类型
- 如何在 Linux 下使用 c++ 知道文件是否被其他进程使用?
- 使用 g++ 编译时列出所有 cpp/cc 文件是否正常?
- 如何检查文件是否复制成功?(便携式解决方案)C++
- 如何检查 win32 exe 文件是否已运行?(使用 win32 API 代码)
- 如何检查每个头文件是否包含必需的包含文件?
- 为许多类可能需要的所有常量变量制作独立的头文件是否是一种很好的做法?
- 使用 CodeBlocks + GCC 构建的可执行文件是否可以在任何 Windows 上运行?
- 如何检查给定文件是否是C++中的有效视频文件?
- 关于使用ifstream在C 中确定文件是否存在的问题
- #include 包含的头文件已包含的头文件是否常见?
- 如何测试文件是否被锁定和/或只读而不打开?
- 检查文件是否具有Windows c ++的可执行权限
- 检查给定的多个文件是否存在
- .txt文件是否已关闭
- 如果给定正确的运行时库,x86 可执行文件是否可以在任何 x86 平台上运行