所以,我是 C++ 的新手,我正在尝试学习继承。我写了一个程序,它只是简单地打印出不同形状的周长,即正方形和三角形。不幸的是,我这样做的方式最终导致了一些重复的代码。这就是我的意思:
#include <iostream>
class Shape {
public:
int sides;
int sideLength;
};
class Square : public Shape {
public:
int sides = 4;
int sideLength = 6;
void calculatePerimeter() {
int perimeter = sideLength * sides;
std::cout << "perimeter length: " << perimeter << std::endl;
}
};
class Triangle : public Shape {
public:
int sides = 3;
int sideLength = 4;
void calculatePerimeter() {
int perimeter = sideLength * sides;
std::cout << "perimeter length: " << perimeter << std::endl;
}
};
int main() {
Square s;
std::cout << "number of sides a square has: " << s.sides << std::endl;
Triangle t;
std::cout << "number of sides a triangle has: " << t.sides << std::endl;
s.calculatePerimeter();
t.calculatePerimeter();
}
如您所见,在 Square 和 Triangle 类中使用了 calculatePerimeter
函数。将它放在 Shape 类中并调用它会导致输出为 0。我怎样才能使它更有效率,这样我就不必为我制作的每个形状类复制/粘贴它?
最佳答案
当您使用继承时,您会在基类中考虑常见的行为和状态,并使派生类使用其特定功能扩展此状态和行为。
从 Shape 中删除 sides 和 sideLength 成员。相反,在类 Shape 中提供返回这些值的虚函数,并让派生类覆盖它们。
Move 方法计算周长到类 Shape,并使用 getSides() 和 getSideLength() 实现
#include <iostream> class Shape { public: virtual int getSides() = 0; virtual int getSideLength() = 0; void calculatePerimeter() { int perimeter = getSideLength() * getSides(); std::cout << "perimeter length: " << perimeter << std::endl; } }; class Square : public Shape { public: virtual int getSides() { return 4; } virtual int getSideLength() { return 6; } }; class Triangle : public Shape { public: virtual int getSides() { return 3; } virtual int getSideLength() { return 4; } };
这就是所谓的模板方法设计模式(不要与 C++ 的模板函数概念混淆,后者是该语言特有的完全不相关的概念)。
关于c++ - 编写此代码的更有效方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33272859/