※これは自分用のメモです※
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;
}
仮想関数テーブルを正しく使うには、きちんとクラスのポインタからメンバ関数を指定してあげなければならないようです!!!