面试题答案
一键面试1. 头文件和源文件结构设计
头文件(math_operations.h)
#ifndef MATH_OPERATIONS_H
#define MATH_OPERATIONS_H
// 函数声明
double add(double a, double b);
double subtract(double a, double b);
double multiply(double a, double b);
double divide(double a, double b);
#endif // MATH_OPERATIONS_H
这里使用 #ifndef
、#define
和 #endif
预处理指令来防止头文件的重复包含。
源文件(math_operations.cpp)
#include "math_operations.h"
// 加法函数定义
double add(double a, double b) {
return a + b;
}
// 减法函数定义
double subtract(double a, double b) {
return a - b;
}
// 乘法函数定义
double multiply(double a, double b) {
return a * b;
}
// 除法函数定义,考虑除数为零的情况
double divide(double a, double b) {
if (b == 0) {
// 这里可以选择抛出异常或者返回一个特殊值,例如 std::numeric_limits<double>::quiet_NaN()
throw std::invalid_argument("除数不能为零");
}
return a / b;
}
2. 在其他模块中调用这些函数
假设在另一个模块 main_module.cpp
中调用 math_operations
模块的函数,代码如下:
#include <iostream>
#include "math_operations.h"
int main() {
double num1 = 10.0;
double num2 = 5.0;
std::cout << "加法结果: " << add(num1, num2) << std::endl;
std::cout << "减法结果: " << subtract(num1, num2) << std::endl;
std::cout << "乘法结果: " << multiply(num1, num2) << std::endl;
try {
std::cout << "除法结果: " << divide(num1, num2) << std::endl;
} catch (const std::invalid_argument& e) {
std::cerr << "错误: " << e.what() << std::endl;
}
return 0;
}
在其他模块中,只需要包含 math_operations.h
头文件,就可以调用其中声明的函数。在编译时,需要将 math_operations.cpp
和调用模块的源文件(如 main_module.cpp
)一起编译链接,以确保函数的定义能被找到。例如,在命令行下使用 g++ main_module.cpp math_operations.cpp -o main
进行编译链接,生成可执行文件 main
。