在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++代碼結構,使其更易于閱讀和維護。