【问题标题】:Example of polymorphism working with data structure in C++ based on php example基于php示例的C++中数据结构的多态性示例
【发布时间】:2012-11-04 04:08:03
【问题描述】:

我正在学习多态,我熟悉php。

我从https://stackoverflow.com/a/749738/80353 发现了这个优秀的例子。转载如下。

如何用 C++ 编写相同的代码?

我自己编写时遇到问题,因为我相信(我可能错了)C++ 中的数据结构是严格的。

您必须在 C++ 中的链表或数组中包含相同类型的所有元素。

所以我认为你需要将猫和狗作为它们的基类存储到数据结构中。

那么我该如何将这个 php 代码 sn-p 写成使用严格数据结构的 C++ 代码 sn-p,它只能存储 1 种数据类型的元素?

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>';
}

【问题讨论】:

  • 不是 C++ 程序员,但我听说您可以拥有 Animals 的列表,并且仍然使用 Animal 子类(例如 Cats 和 Dogs)填充它。
  • 你能举个例子吗?我不熟悉 C++ 语法,谷歌搜索“动态列表 C++”对我没有多大帮助。

标签: php c++ polymorphism


【解决方案1】:

好吧,您可以使用带有抽象类的指针,使用纯虚方法,如下所示:

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;
}

【讨论】:

  • 感谢您的尝试。但我更喜欢直接翻译上面的 php 代码,这样我更容易理解多态性。
  • @kimsia 没有人愿意为您编写代码。如果你想学习如何,你必须自己做。您不会从我编写代码中学到任何东西,但是您将通过自己编写代码来学习如何正确地完成它。我向您展示了如何用 C++ 对其进行编程;因此,我回答了你的问题。如果您希望有人为您编写代码,请为他们提供工作并付钱给他们。
  • 一定是有什么误解。我来这里不是为了摆脱别人,把其他人的代码当作我的。感谢您的回复。
  • @kimsia 我知道,但您显然是在要求其他人为您编写代码。
【解决方案2】:

由于您只询问了存储它们,我将省略Animal、Dog 和Cat 的实现。

vector< shared_ptr<Animal> > animals;
animals.push_back( new Dog("Skip") );
animals.push_back( new Cat("Snowball") );

for( size_t i = 0; i< animals.size(); ++i )
    cout << animals[i]->name << " says: " << animals[i]->speak() << endl;

本质上,您需要存储指向对象的指针。简单来说,shared_ptr&lt;T&gt; 是一个存储指针的类,当不再引用时将其删除。

【讨论】:

    【解决方案3】:

    作为不熟悉C++的人,创建一个index.cpp文件并填写以下内容

    #include <iostream>
    #include <vector>
    #include <memory>
    
    using namespace std;
    
    class Animal {
      public:
        std::string name;
        Animal (const std::string& givenName) : name(givenName) {}
        virtual string speak () = 0;
        virtual ~Animal() {}
    
      };
    
    class Dog: public Animal {
      public:
        Dog (const std::string& givenName) : Animal (givenName) {
    
        }
        string speak ()
          { return "Woof, woof!"; }
      };
    
    class Cat: public Animal {
      public:
        Cat (const std::string& givenName) : Animal (givenName) {
        }
        string speak ()
          { return "Meow..."; }
      };
    
    int main() {
        std::vector<std::unique_ptr<Animal>> animals;
        animals.push_back( std::unique_ptr<Animal>(new Dog("Skip"))  );
        animals.push_back( std::unique_ptr<Animal>(new Cat("Snowball"))  );
    
        for( int i = 0; i< animals.size(); ++i ) {
            cout << animals[i]->name << " says: " << animals[i]->speak() << endl;
        }
    
    }
    

    之后,使用以下命令编译 index.cpp 文件

    c++ index.cpp -std=c++11 -stdlib=libc++
    

    由于在代码中使用了智能指针 unique_ptr,您需要这样做。

    终于可以执行编译后的可执行输出文件了,应该是a.out

    ./a.out
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-07
      相关资源
      最近更新 更多