我正在学习多态,并且熟悉php。
我发现了这个很好的例子https://stackoverflow.com/a/749738/80353 https://stackoverflow.com/a/749738/80353。转载如下。
如何用 C++ 编写相同的代码?
我自己编写它时遇到问题,因为我相信(我可能是错的)C++ 中的数据结构是严格的。
C++ 中的链表或数组中的所有元素必须具有相同类型。
所以我相信你需要将猫和狗作为它们的基类存储到数据结构中。
那么,如何将这段 php 代码片段写入使用严格数据结构(只能存储 1 种数据类型的元素)的 C++ 代码片段呢?
class Animal {
var $name;
function __construct($name) {
$this->name = $name;
}
}
class Dog extends Animal {
function speak() {
return "Woof, woof!";
}
}
class Cat extends Animal {
function speak() {
return "Meow...";
}
}
$animals = array(new Dog('Skip'), new Cat('Snowball'));
foreach($animals as $animal) {
print $animal->name . " says: " . $animal->speak() . '<br>';
}
好吧,您可以使用纯虚方法将指针与抽象类一起使用,如下所示:
class Polygon {
public:
virtual void setValue(int k) = 0; // Declaring our pure virtual method.
};
class Rect : public Polygon {
public:
virtual void setValue(int k); = 0; // Declaring the pure virtual method again.
};
Rect::setValue(int k) { // You must create a setValue() method for every class, since we made a pure virtual method. This is the Polymorphic part.
// Code in here that setValue() method executes.
int foo = a;
std::cout << foo << std::endl;
}
现在您可以访问声明对象指针的方法。
int main() {
Polygon* pSomePolygon = nullptr; // Assuming using C++11.
Rect* pRect = new Rect; // Declare our object.
pSomePolygon = pRect; // Point our pointer to object 'pRect'.
pSomePolygon->setValue(18); // Pointer accesses pRect and uses the pure virtual method.
delete pRect; // Clean up!
return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)