C++ 函数编写与封装方法详解 1. 函数的基本结构 1.1 基本函数定义 1 2 3 4 5 6 7 8 返回类型 函数名(参数列表); 返回类型 函数名(参数列表) { return 返回值; }
1.2 完整示例 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 #include <iostream> using namespace std;int add (int a, int b) ;void printMessage (const string& message) ;int add (int a, int b) { return a + b; } void printMessage (const string& message) { cout << "Message: " << message << endl; } int main () { int result = add (5 , 3 ); printMessage ("Hello World" ); return 0 ; }
2. 参数传递方式 2.1 值传递 (Pass by Value) 1 2 3 4 5 6 7 8 9 void modifyValue (int x) { x = 100 ; } int main () { int a = 10 ; modifyValue (a); cout << a; }
2.2 引用传递 (Pass by Reference) 1 2 3 4 5 6 7 8 9 void modifyReference (int &x) { x = 100 ; } int main () { int a = 10 ; modifyReference (a); cout << a; }
2.3 常量引用传递 (Pass by Const Reference) 1 2 3 4 5 6 void printLargeObject (const vector<int >& vec) { for (const auto & item : vec) { cout << item << " " ; } }
2.4 指针传递 (Pass by Pointer) 1 2 3 4 5 6 7 8 9 10 11 void modifyPointer (int * ptr) { if (ptr) { *ptr = 100 ; } } int main () { int a = 10 ; modifyPointer (&a); cout << a; }
3. 函数重载 (Function Overloading) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 class Calculator {public : int add (int a, int b) { return a + b; } double add (double a, double b) { return a + b; } string add (const string& a, const string& b) { return a + b; } int add (int a, int b, int c) { return a + b + c; } }; Calculator calc; cout << calc.add (1 , 2 ); cout << calc.add (1.5 , 2.5 ); cout << calc.add ("Hello" , " World" );
4. 默认参数 (Default Parameters) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 class Student {public : Student (string name = "Unknown" , int age = 18 , double gpa = 3.0 ) : name (name), age (age), gpa (gpa) {} void displayInfo (string prefix = "Student: " ) { cout << prefix << name << ", Age: " << age << ", GPA: " << gpa << endl; } private : string name; int age; double gpa; }; Student s1; Student s2 ("Alice" ) ; Student s3 ("Bob" , 20 ) ; Student s4 ("Charlie" , 22 , 3.8 ) ;
5. 内联函数 (Inline Functions) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 inline int square (int x) { return x * x; } inline int max (int a, int b) { return (a > b) ? a : b; } class MathUtils {public : int cube (int x) { return x * x * x; } inline double circleArea (double radius) { return 3.14159 * radius * radius; } };
6. 模板函数 (Template Functions) 6.1 基础模板函数 1 2 3 4 5 6 7 8 9 10 11 12 13 14 template <typename T>T getMax (T a, T b) { return (a > b) ? a : b; } template <typename T1, typename T2>auto addMixed (T1 a, T2 b) -> decltype (a + b) { return a + b; } cout << getMax (10 , 20 ); cout << getMax (3.14 , 2.71 ); cout << getMax ('a' , 'z' );
6.2 模板特化 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 template <typename T>class Storage {public : void store (const T& data) { cout << "Storing generic type: " << data << endl; } }; template <>class Storage <string> {public : void store (const string& data) { cout << "Storing string: \"" << data << "\"" << endl; } };
7. Lambda 表达式 7.1 基础Lambda 1 2 3 4 5 6 7 8 9 auto square = [](int x) { return x * x; };auto greet = [](const string& name) { return "Hello, " + name + "!" ; }; cout << square (5 ); cout << greet ("World" );
7.2 捕获列表 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 class LambdaDemo {private : int multiplier = 10 ; public : void demonstrate () { int localVar = 5 ; auto captureByValue = [localVar](int x) { return x + localVar; }; auto captureByReference = [&localVar](int x) { localVar = x; return localVar; }; auto captureThis = [this ](int x) { return x * multiplier; }; auto mixedCapture = [=, &localVar](int x) { return x + localVar + multiplier; }; } };
8. 函数指针和函数对象 8.1 函数指针 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 int add (int a, int b) { return a + b; }int multiply (int a, int b) { return a * b; }using MathOperation = int (*)(int , int );class Calculator {public : int calculate (MathOperation op, int a, int b) { return op (a, b); } }; Calculator calc; cout << calc.calculate (add, 5 , 3 ); cout << calc.calculate (multiply, 5 , 3 );
8.2 函数对象 (Functor) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 class Adder {private : int baseValue; public : Adder (int base) : baseValue (base) {} int operator () (int value) const { return baseValue + value; } }; class Comparator {public : bool operator () (int a, int b) const { return a > b; } }; Adder add5 (5 ) ;cout << add5 (10 ); vector<int > numbers = {3 , 1 , 4 , 1 , 5 }; sort (numbers.begin (), numbers.end (), Comparator ());
9. 成员函数封装 9.1 类的基本封装 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 class BankAccount {private : string accountNumber; double balance; bool isValidAmount (double amount) const { return amount > 0 ; } public : BankAccount (const string& accNum, double initialBalance = 0.0 ) : accountNumber (accNum), balance (initialBalance) {} string getAccountNumber () const { return accountNumber; } double getBalance () const { return balance; } bool deposit (double amount) { if (!isValidAmount (amount)) return false ; balance += amount; return true ; } bool withdraw (double amount) { if (!isValidAmount (amount) || amount > balance) return false ; balance -= amount; return true ; } static string getBankName () { return "MyBank" ; } };
9.2 接口和实现分离 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 class IMathOperations {public : virtual ~IMathOperations () = default ; virtual double calculate (double a, double b) = 0 ; virtual string getName () const = 0 ; }; class Addition : public IMathOperations {public : double calculate (double a, double b) override { return a + b; } string getName () const override { return "Addition" ; } }; class Multiplication : public IMathOperations {public : double calculate (double a, double b) override { return a * b; } string getName () const override { return "Multiplication" ; } };
10. 现代C++特性 10.1 constexpr 函数 1 2 3 4 5 6 7 8 9 10 11 12 constexpr int factorial (int n) { return (n <= 1 ) ? 1 : n * factorial (n - 1 ); } constexpr int fibonacci (int n) { return (n <= 1 ) ? n : fibonacci (n - 1 ) + fibonacci (n - 2 ); } constexpr int fact5 = factorial (5 ); constexpr int fib10 = fibonacci (10 );
10.2 noexcept 函数 1 2 3 4 5 6 7 8 9 10 11 12 13 14 class SafeCalculator {public : int safeDivide (int a, int b) noexcept { if (b == 0 ) return 0 ; return a / b; } template <typename T> void processData (T&& data) noexcept (noexcept (data.process())) { data.process (); } };
11. 错误处理和异常安全 11.1 异常处理 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 class FileProcessor {public : void processFile (const string& filename) { ifstream file (filename) ; if (!file.is_open ()) { throw runtime_error ("Cannot open file: " + filename); } try { string line; while (getline (file, line)) { processLine (line); } } catch (const exception& e) { file.close (); throw ; } } private : void processLine (const string& line) { if (line.empty ()) { throw invalid_argument ("Empty line encountered" ); } } };
最佳实践总结
单一职责原则 :每个函数只做一件事
合理的参数传递 :小对象传值,大对象传const引用
清晰的命名 :函数名应该明确表达其功能
适当的封装 :使用private保护内部状态
异常安全 :确保资源正确释放
文档注释 :为公共接口提供清晰的文档
测试覆盖 :为关键函数编写单元测试
这些方法可以帮助你编写出更清晰、更安全、更易维护的C++代码。
Author:
Lyxy-szs
Permalink:
http://lyxy-szs.github.io/2025/11/27/Cpp-Faction/
Slogan:
永远相信美好的事情即将發生 ?