c++ - 我是否正确使用了头文件?
问题描述
我想了解 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);
}
我的数学.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; }
}
主文件
#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
命名空间中。有两种方法可以做到这一点:
方法一
正如你所做的那样。
方法二
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; }
就编译器而言,这两种方法完全相同。您可以使用任何一种方法。您甚至可以将两者混合使用。没有什么不妥。
在头文件中实现没有类的函数也是一个很好的约定吗?
这个问题的答案相当广泛。这不是解决它的最佳位置。
推荐阅读
- excel - 是否可以对一系列数字求和并更改每个数字?
- java - Java 列表
该条件添加可选 - android - 错误:程序类型已存在:android.arch.lifecycle.ViewModelStore
- kerberos - 重复出现的问题 - 启用 Kerberos 后,UI 中的 Ambari 服务列表中缺少 Kerberos 服务
- c# - XNA C#:Player 类下列表中的 Projectile 对象,Enemy 类无法识别
- wix - WIX Installer Preserve config file On major upgrade early Scheduling
- audio - 在将 OGG 音频转换为 MP3 时,FFMPEG 在文件开头添加了额外的内容
- r - 如果任何行包含子字符串,则标记
- java - 在 Android 上使用 cache2k 时出现 java.lang.NoClassDefFoundError
- python-3.x - 如何将极坐标图划分为 12 个分区?