C++运算符与表达式:构建高效计算逻辑的核心

一、学习目标与重点
本章将深入探讨C++中运算符与表达式的核心概念和使用方法。通过学习,你将能够:
二、运算符的分类与优先级
2.1 运算符的分类
C++运算符可分为以下几类:
- 算术运算符:用于数值计算
- 关系运算符:用于比较操作
- 逻辑运算符:用于逻辑运算
- 位运算符:用于位级操作
- 赋值运算符:用于赋值操作
- 条件运算符:用于条件判断
- 逗号运算符:用于分隔多个表达式
2.2 运算符的优先级与结合性
| 1 | 括号 | () [] -> . | 左到右 |
| 2 | 一元运算符 | ! ~ ++ – + – * & sizeof | 右到左 |
| 3 | 乘法运算符 | * / % | 左到右 |
| 4 | 加法运算符 | + – | 左到右 |
| 5 | 位移运算符 | << >> | 左到右 |
| 6 | 关系运算符 | < <= > >= | 左到右 |
| 7 | 相等运算符 | == != | 左到右 |
| 8 | 位与运算符 | & | 左到右 |
| 9 | 位异或运算符 | ^ | 左到右 |
| 10 | 位或运算符 | | | 左到右 |
| 11 | 逻辑与运算符 | && | 左到右 |
| 12 | 逻辑或运算符 | || | 左到右 |
| 13 | 条件运算符 | ? : | 右到左 |
| 14 | 赋值运算符 | = += -= *= /= %= <<= >>= &= ^= |= | 右到左 |
| 15 | 逗号运算符 | , | 左到右 |
三、基本运算符的使用
3.1 算术运算符
#include <iostream>
int main() {
int a = 10, b = 3;
std::cout << "=== 算术运算符示例 ===" << std::endl;
std::cout << "a + b = " << a + b << std::endl; // 加法
std::cout << "a – b = " << a – b << std::endl; // 减法
std::cout << "a * b = " << a * b << std::endl; // 乘法
std::cout << "a / b = " << a / b << std::endl; // 除法(整数除法)
std::cout << "a % b = " << a % b << std::endl; // 取余
double c = 10.0, d = 3.0;
std::cout << "c / d = " << c / d << std::endl; // 浮点数除法
return 0;
}
3.2 关系运算符
#include <iostream>
int main() {
int a = 10, b = 20;
std::cout << "=== 关系运算符示例 ===" << std::endl;
std::cout << "a < b = " << (a < b) << std::endl; // 小于
std::cout << "a > b = " << (a > b) << std::endl; // 大于
std::cout << "a <= b = " << (a <= b) << std::endl; // 小于等于
std::cout << "a >= b = " << (a >= b) << std::endl; // 大于等于
std::cout << "a == b = " << (a == b) << std::endl; // 等于
std::cout << "a != b = " << (a != b) << std::endl; // 不等于
return 0;
}
3.3 逻辑运算符
#include <iostream>
int main() {
bool x = true, y = false;
std::cout << "=== 逻辑运算符示例 ===" << std::endl;
std::cout << "x && y = " << (x && y) << std::endl; // 逻辑与
std::cout << "x || y = " << (x || y) << std::endl; // 逻辑或
std::cout << "!x = " << (!x) << std::endl; // 逻辑非
int a = 10, b = 20;
std::cout << "(a > 5 && b < 30) = " << (a > 5 && b < 30) << std::endl;
return 0;
}
3.4 位运算符
#include <iostream>
void printBinary(int num) {
if (num > 1) {
printBinary(num / 2);
}
std::cout << (num % 2);
}
int main() {
int a = 6, b = 3;
std::cout << "=== 位运算符示例 ===" << std::endl;
std::cout << "a = " << a << " ("; printBinary(a); std::cout << ")" << std::endl;
std::cout << "b = " << b << " ("; printBinary(b); std::cout << ")" << std::endl;
std::cout << "a & b = " << (a & b) << " ("; printBinary(a & b); std::cout << ")" << std::endl; // 位与
std::cout << "a | b = " << (a | b) << " ("; printBinary(a | b); std::cout << ")" << std::endl; // 位或
std::cout << "a ^ b = " << (a ^ b) << " ("; printBinary(a ^ b); std::cout << ")" << std::endl; // 位异或
std::cout << "~a = " << (~a) << " ("; printBinary(~a); std::cout << ")" << std::endl; // 位非
std::cout << "a << 1 = " << (a << 1) << " ("; printBinary(a << 1); std::cout << ")" << std::endl; // 左移
std::cout << "a >> 1 = " << (a >> 1) << " ("; printBinary(a >> 1); std::cout << ")" << std::endl; // 右移
return 0;
}
四、复合赋值运算符
#include <iostream>
int main() {
int a = 10;
std::cout << "=== 复合赋值运算符示例 ===" << std::endl;
std::cout << "初始值 a = " << a << std::endl;
a += 5; // 等价于 a = a + 5
std::cout << "a += 5 后: " << a << std::endl;
a -= 3; // 等价于 a = a – 3
std::cout << "a -= 3 后: " << a << std::endl;
a *= 2; // 等价于 a = a * 2
std::cout << "a *= 2 后: " << a << std::endl;
a /= 4; // 等价于 a = a / 4
std::cout << "a /= 4 后: " << a << std::endl;
a %= 2; // 等价于 a = a % 2
std::cout << "a %= 2 后: " << a << std::endl;
a = 6;
a &= 3; // 等价于 a = a & 3
std::cout << "a &= 3 后: " << a << std::endl;
a = 6;
a |= 3; // 等价于 a = a | 3
std::cout << "a |= 3 后: " << a << std::endl;
a = 6;
a ^= 3; // 等价于 a = a ^ 3
std::cout << "a ^= 3 后: " << a << std::endl;
a = 6;
a <<= 1; // 等价于 a = a << 1
std::cout << "a <<= 1 后: " << a << std::endl;
a = 6;
a >>= 1; // 等价于 a = a >> 1
std::cout << "a >>= 1 后: " << a << std::endl;
return 0;
}
五、条件运算符与逗号运算符
5.1 条件运算符
#include <iostream>
int main() {
int a = 10, b = 20;
std::cout << "=== 条件运算符示例 ===" << std::endl;
// 基本使用
int max = (a > b) ? a : b;
std::cout << "max(" << a << ", " << b << ") = " << max << std::endl;
// 嵌套使用
int c = 15;
int largest = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);
std::cout << "largest(" << a << ", " << b << ", " << c << ") = " << largest << std::endl;
// 作为函数参数
std::cout << "min(" << a << ", " << b << ") = " << ((a < b) ? a : b) << std::endl;
return 0;
}
5.2 逗号运算符
#include <iostream>
int main() {
std::cout << "=== 逗号运算符示例 ===" << std::endl;
// 基本使用
int x, y;
y = (x = 5, x * 2); // 结果为10
std::cout << "y = (x = 5, x * 2) = " << y << std::endl;
// 在循环中使用
int i, j;
for (i = 0, j = 10; i < j; i++, j—) {
std::cout << "i = " << i << ", j = " << j << std::endl;
}
// 在函数参数中使用
int a, b, c;
a = 1, b = 2, c = 3;
std::cout << "sum = " << (a + b + c) << std::endl;
return 0;
}
六、运算符重载的基本概念
6.1 重载的定义
运算符重载允许我们为自定义类型定义运算符的行为。
#include <iostream>
#include <string>
class Complex {
private:
double real;
double imaginary;
public:
Complex(double r = 0.0, double i = 0.0) : real(r), imaginary(i) {}
// 重载加法运算符
Complex operator+(const Complex& other) const {
return Complex(real + other.real, imaginary + other.imaginary);
}
// 重载减法运算符
Complex operator–(const Complex& other) const {
return Complex(real – other.real, imaginary – other.imaginary);
}
// 重载乘法运算符
Complex operator*(const Complex& other) const {
return Complex(
real * other.real – imaginary * other.imaginary,
real * other.imaginary + imaginary * other.real
);
}
// 重载输出运算符(友元函数)
friend std::ostream& operator<<(std::ostream& os, const Complex& c) {
os << c.real << " + " << c.imaginary << "i";
return os;
}
};
int main() {
std::cout << "=== 运算符重载示例 ===" << std::endl;
Complex c1(1.0, 2.0);
Complex c2(3.0, 4.0);
std::cout << "c1 = " << c1 << std::endl;
std::cout << "c2 = " << c2 << std::endl;
Complex sum = c1 + c2;
std::cout << "c1 + c2 = " << sum << std::endl;
Complex difference = c1 – c2;
std::cout << "c1 – c2 = " << difference << std::endl;
Complex product = c1 * c2;
std::cout << "c1 * c2 = " << product << std::endl;
return 0;
}
6.2 重载的规则
七、表达式的求值与优化
7.1 表达式的求值顺序
#include <iostream>
int main() {
std::cout << "=== 表达式求值顺序示例 ===" << std::endl;
int a = 5;
int b = ++a * 2; // 先自增a,再相乘
std::cout << "a = " << a << ", b = " << b << std::endl;
int c = 5;
int d = c++ * 2; // 先相乘,再自增c
std::cout << "c = " << c << ", d = " << d << std::endl;
int e = 5, f = 5;
int g = (e++) + (++f); // e先使用后自增,f先自增后使用
std::cout << "e = " << e << ", f = " << f << ", g = " << g << std::endl;
return 0;
}
7.2 表达式的优化
#include <iostream>
#include <chrono>
// 优化前
int calculate1(int n) {
int result = 0;
for (int i = 0; i < n; i++) {
result += i * (i + 1);
}
return result;
}
// 优化后(提取重复计算)
int calculate2(int n) {
int result = 0;
int term;
for (int i = 0; i < n; i++) {
term = i;
result += term * (term + 1);
}
return result;
}
// 优化后(数学优化)
int calculate3(int n) {
return n * (n + 1) * (2 * n + 1) / 6 + n * (n + 1) / 2;
}
int main() {
const int n = 10000000;
std::cout << "=== 表达式优化示例 ===" << std::endl;
auto start = std::chrono::high_resolution_clock::now();
int result1 = calculate1(n);
auto end = std::chrono::high_resolution_clock::now();
auto duration1 = std::chrono::duration_cast<std::chrono::milliseconds>(end – start);
start = std::chrono::high_resolution_clock::now();
int result2 = calculate2(n);
end = std::chrono::high_resolution_clock::now();
auto duration2 = std::chrono::duration_cast<std::chrono::milliseconds>(end – start);
start = std::chrono::high_resolution_clock::now();
int result3 = calculate3(n);
end = std::chrono::high_resolution_clock::now();
auto duration3 = std::chrono::duration_cast<std::chrono::milliseconds>(end – start);
std::cout << "calculate1耗时: " << duration1.count() << "ms" << std::endl;
std::cout << "calculate2耗时: " << duration2.count() << "ms" << std::endl;
std::cout << "calculate3耗时: " << duration3.count() << "ms" << std::endl;
std::cout << "结果: " << result1 << ", " << result2 << ", " << result3 << std::endl;
return 0;
}
八、综合案例:实现一个科学计算器
8.1 项目结构
ScientificCalculator/
├── include/
│ └── Calculator.h
├── src/
│ ├── Calculator.cpp
│ └── main.cpp
└── build/
8.2 核心代码
// include/Calculator.h
#ifndef CALCULATOR_H
#define CALCULATOR_H
#include <cmath>
#include <stdexcept>
#include <string>
class Calculator {
public:
// 基础运算
static double add(double a, double b);
static double subtract(double a, double b);
static double multiply(double a, double b);
static double divide(double a, double b);
// 科学运算
static double square(double x);
static double squareRoot(double x);
static double power(double base, double exponent);
static double factorial(double x);
static double sine(double x);
static double cosine(double x);
static double tangent(double x);
// 高级运算
static double log10(double x);
static double naturalLog(double x);
static double absolute(double x);
static double roundToInt(double x);
// 错误处理
static bool isValidDouble(const std::string& str);
static double stringToDouble(const std::string& str);
};
#endif // CALCULATOR_H
// src/Calculator.cpp
#include <Calculator.h>
#include <sstream>
double Calculator::add(double a, double b) {
return a + b;
}
double Calculator::subtract(double a, double b) {
return a – b;
}
double Calculator::multiply(double a, double b) {
return a * b;
}
double Calculator::divide(double a, double b) {
if (b == 0) {
throw std::invalid_argument("除数不能为零");
}
return a / b;
}
double Calculator::square(double x) {
return x * x;
}
double Calculator::squareRoot(double x) {
if (x < 0) {
throw std::invalid_argument("负数不能开平方");
}
return std::sqrt(x);
}
double Calculator::power(double base, double exponent) {
return std::pow(base, exponent);
}
double Calculator::factorial(double x) {
if (x < 0) {
throw std::invalid_argument("负数没有阶乘");
}
if (x == 0 || x == 1) {
return 1;
}
if (x != static_cast<int>(x)) {
// 使用伽马函数计算非整数阶乘
return std::tgamma(x + 1);
}
double result = 1;
for (int i = 2; i <= static_cast<int>(x); i++) {
result *= i;
}
return result;
}
double Calculator::sine(double x) {
return std::sin(x);
}
double Calculator::cosine(double x) {
return std::cos(x);
}
double Calculator::tangent(double x) {
return std::tan(x);
}
double Calculator::log10(double x) {
if (x <= 0) {
throw std::invalid_argument("对数的底数必须大于零");
}
return std::log10(x);
}
double Calculator::naturalLog(double x) {
if (x <= 0) {
throw std::invalid_argument("自然对数的底数必须大于零");
}
return std::log(x);
}
double Calculator::absolute(double x) {
return std::abs(x);
}
double Calculator::roundToInt(double x) {
return std::round(x);
}
bool Calculator::isValidDouble(const std::string& str) {
std::istringstream iss(str);
double d;
return iss >> d && iss.eof();
}
double Calculator::stringToDouble(const std::string& str) {
if (!isValidDouble(str)) {
throw std::invalid_argument("无效的数字格式");
}
return std::stod(str);
}
// src/main.cpp
#include <iostream>
#include <string>
#include <Calculator.h>
void showMenu() {
std::cout << "\\n=== 科学计算器 ===" << std::endl;
std::cout << "1. 加法" << std::endl;
std::cout << "2. 减法" << std::endl;
std::cout << "3. 乘法" << std::endl;
std::cout << "4. 除法" << std::endl;
std::cout << "5. 平方" << std::endl;
std::cout << "6. 平方根" << std::endl;
std::cout << "7. 幂运算" << std::endl;
std::cout << "8. 阶乘" << std::endl;
std::cout << "9. 正弦" << std::endl;
std::cout << "10. 余弦" << std::endl;
std::cout << "11. 正切" << std::endl;
std::cout << "12. 常用对数" << std::endl;
std::cout << "13. 自然对数" << std::endl;
std::cout << "14. 绝对值" << std::endl;
std::cout << "15. 四舍五入" << std::endl;
std::cout << "0. 退出" << std::endl;
std::cout << "请输入操作编号: ";
}
int main() {
int choice;
std::string input;
double x, y;
do {
showMenu();
std::cin >> choice;
try {
switch (choice) {
case 1:
std::cout << "请输入两个数(用空格隔开): ";
std::cin >> x >> y;
std::cout << "结果: " << Calculator::add(x, y) << std::endl;
break;
case 2:
std::cout << "请输入两个数(用空格隔开): ";
std::cin >> x >> y;
std::cout << "结果: " << Calculator::subtract(x, y) << std::endl;
break;
case 3:
std::cout << "请输入两个数(用空格隔开): ";
std::cin >> x >> y;
std::cout << "结果: " << Calculator::multiply(x, y) << std::endl;
break;
case 4:
std::cout << "请输入两个数(用空格隔开): ";
std::cin >> x >> y;
std::cout << "结果: " << Calculator::divide(x, y) << std::endl;
break;
case 5:
std::cout << "请输入一个数: ";
std::cin >> x;
std::cout << "结果: " << Calculator::square(x) << std::endl;
break;
case 6:
std::cout << "请输入一个数: ";
std::cin >> x;
std::cout << "结果: " << Calculator::squareRoot(x) << std::endl;
break;
case 7:
std::cout << "请输入底数和指数(用空格隔开): ";
std::cin >> x >> y;
std::cout << "结果: " << Calculator::power(x, y) << std::endl;
break;
case 8:
std::cout << "请输入一个数: ";
std::cin >> x;
std::cout << "结果: " << Calculator::factorial(x) << std::endl;
break;
case 9:
std::cout << "请输入角度(弧度): ";
std::cin >> x;
std::cout << "结果: " << Calculator::sine(x) << std::endl;
break;
case 10:
std::cout << "请输入角度(弧度): ";
std::cin >> x;
std::cout << "结果: " << Calculator::cosine(x) << std::endl;
break;
case 11:
std::cout << "请输入角度(弧度): ";
std::cin >> x;
std::cout << "结果: " << Calculator::tangent(x) << std::endl;
break;
case 12:
std::cout << "请输入一个数: ";
std::cin >> x;
std::cout << "结果: " << Calculator::log10(x) << std::endl;
break;
case 13:
std::cout << "请输入一个数: ";
std::cin >> x;
std::cout << "结果: " << Calculator::naturalLog(x) << std::endl;
break;
case 14:
std::cout << "请输入一个数: ";
std::cin >> x;
std::cout << "结果: " << Calculator::absolute(x) << std::endl;
break;
case 15:
std::cout << "请输入一个数: ";
std::cin >> x;
std::cout << "结果: " << Calculator::roundToInt(x) << std::endl;
break;
case 0:
std::cout << "退出计算器" << std::endl;
break;
default:
std::cout << "无效的操作编号" << std::endl;
break;
}
} catch (const std::exception& e) {
std::cout << "错误: " << e.what() << std::endl;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\\n');
}
if (choice != 0) {
std::cout << "\\n按Enter键继续…";
std::cin.ignore();
std::cin.get();
}
} while (choice != 0);
return 0;
}
8.3 项目构建与运行
# 创建构建目录
mkdir -p build && cd build
# 配置CMake
cmake -DCMAKE_BUILD_TYPE=Release ..
# 编译项目
cmake –build . –config Release
# 运行计算器
./ScientificCalculator
九、总结与练习
9.1 本章总结
本章介绍了C++运算符与表达式的核心概念和使用方法,包括:
网硕互联帮助中心



评论前必须登录!
注册