在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++编程中实现代码复用,提高代码的可维护性和可读性。