在C++編程中,實現代碼復用有多種方法。以下是一些建議:
#include <iostream>
// 函數聲明
int add(int a, int b);
int main() {
int result = add(3, 4);
std::cout << "3 + 4 = " << result << std::endl;
return 0;
}
// 函數定義
int add(int a, int b) {
return a + b;
}
#include <iostream>
class Rectangle {
public:
Rectangle(double width, double height);
double area() const;
private:
double width_;
double height_;
};
Rectangle::Rectangle(double width, double height) : width_(width), height_(height) {}
double Rectangle::area() const {
return width_ * height_;
}
int main() {
Rectangle rect(3.0, 4.0);
std::cout << "矩形的面積: " << rect.area() << std::endl;
return 0;
}
#include <iostream>
// 模板函數聲明
template <typename T>
T add(T a, T b);
int main() {
int intResult = add(3, 4);
double doubleResult = add(3.0, 4.0);
std::cout << "3 + 4 = " << intResult << std::endl;
std::cout << "3.0 + 4.0 = " << doubleResult << std::endl;
return 0;
}
// 模板函數定義
template <typename T>
T add(T a, T b) {
return a + b;
}
math_functions.h
:
#pragma once
int add(int a, int b);
double add(double a, double b);
math_functions.cpp
:
#include "math_functions.h"
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
main.cpp
:
#include <iostream>
#include "math_functions.h"
int main() {
int intResult = add(3, 4);
double doubleResult = add(3.0, 4.0);
std::cout << "3 + 4 = " << intResult << std::endl;
std::cout << "3.0 + 4.0 = " << doubleResult << std::endl;
return 0;
}
通過使用這些方法,可以在C++編程中實現代碼復用,提高代碼的可維護性和可讀性。