1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C++:基底クラスの配列から派生クラスのメソッドを呼び出す

Last updated at Posted at 2018-02-24

※これは自分用のメモです※
C/C++を始めたばかりの超初心者(というか、プログラミング初心者)なのであんまり真面目に見ないでください。

#間違い#

inheritance.cpp
#include <iostream>
#include <vector>

class Sounds{
public:
  virtual void pulse(){
    std::cout << "This is Super Class." << std::endl;
  }
};


class Sin : public Sounds{
private:
  std::string sound;

public:
  Sin(){
    this->sound = "po---------";
  }

  Sin(const std::string& sound){
    this->sound = sound;
  }

  void pulse() override{
    std::cout << this->sound << std::endl;
  }
};


class Noise : public Sounds{
private:
  std::string sound;

public:
  Noise(){
    this->sound = "za---------";
  }

  Noise(const std::string& sound){
    this->sound = sound;
  }

  void pulse() override{
    std::cout << this->sound << std::endl;
  }
};

int main(){
  Sin s1, s2("aa---------");
  Noise n1, n2("bo---------");
  std::vector<Sounds> sounds;

  sounds.emplace_back(s1);
  sounds.emplace_back(s2);
  sounds.emplace_back(n1);
  sounds.emplace_back(n2);

  for(auto i : sounds){
    i.pulse();
  }

  return 0;
}
出力
This is Super Class.
This is Super Class.
This is Super Class.
This is Super Class.

#正解

inheritance.cpp

.../*省略*/

int main(){
  Sin s1, s2("aa---------");
  Noise n1, n2("bo---------");
  std::vector<Sounds *> sounds;

  sounds.emplace_back(&s1);
  sounds.emplace_back(&s2);
  sounds.emplace_back(&n1);
  sounds.emplace_back(&n2);

  for(auto&& i : sounds){
    i->pulse();
  }

  return 0;
}
出力
po---------
aa---------
za---------
bo---------

↓↓↓もちろん、これでもOKだった↓↓↓


int main(){
  std::vector<Sounds *> sounds;

  sounds.emplace_back(new Sin());
  sounds.emplace_back(new Sin("aa---------"));
  sounds.emplace_back(new Noise());
  sounds.emplace_back(new Noise("bo---------"));

  for(auto&& i : sounds){
    i->pulse();
  }

  return 0;
}

仮想関数テーブルを正しく使うには、きちんとクラスのポインタからメンバ関数を指定してあげなければならないようです!!!

1
2
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?