在C++中,分支(branch)通常是通过条件语句(如if-else)实现的。为了简化代码结构,你可以遵循以下建议:
void process_positive_number(int number) {
// 处理正数的逻辑
}
void process_negative_number(int number) {
// 处理负数的逻辑
}
int main() {
int number = // ... 获取输入的数字
if (number > 0) {
process_positive_number(number);
} else if (number < 0) {
process_negative_number(number);
} else {
// 处理零的逻辑
}
return 0;
}
class Shape {
public:
virtual double area() const = 0;
};
class Circle : public Shape {
public:
double radius;
Circle(double r) : radius(r) {}
double area() const override {
return 3.14 * radius * radius;
}
};
class Rectangle : public Shape {
public:
double width, height;
Rectangle(double w, double h) : width(w), height(h) {}
double area() const override {
return width * height;
}
};
void draw_shape(const Shape& shape) {
std::cout << "Area: " << shape.area() << std::endl;
}
int main() {
Circle circle(5);
Rectangle rectangle(4, 6);
draw_shape(circle);
draw_shape(rectangle);
return 0;
}
class Algorithm {
public:
virtual double calculate(double x, double y) const = 0;
};
class AddAlgorithm : public Algorithm {
public:
double calculate(double x, double y) const override {
return x + y;
}
};
class MultiplyAlgorithm : public Algorithm {
public:
double calculate(double x, double y) const override {
return x * y;
}
};
double perform_operation(double x, double y, const Algorithm& algorithm) {
return algorithm.calculate(x, y);
}
int main() {
double x = 5, y = 3;
AddAlgorithm add_algorithm;
MultiplyAlgorithm multiply_algorithm;
std::cout << "Add: " << perform_operation(x, y, add_algorithm) << std::endl;
std::cout << "Multiply: " << perform_operation(x, y, multiply_algorithm) << std::endl;
return 0;
}
遵循这些建议可以帮助你简化C++代码结构,使其更易于阅读和维护。