Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //#include <iostream>
- //
- //using namespace std;
- //
- //class Animal
- //{
- //public:
- //
- // Animal(const string& type):type_(type){}
- //
- // void Eat(const string& fruit)
- // {
- // cout<<type_<<" eats "<<fruit<<endl;
- // }
- //
- //private:
- // const string type_;
- //};
- //
- //class Cat : public Animal
- //{
- //public:
- //
- // Cat():Animal("cat"){}
- //
- //
- // void Meow() const
- // {
- // cout << "Meow! " << endl;
- // }
- //};
- //
- //class Dog : public Animal
- //{
- //public:
- //
- // Dog():Animal("dog"){}
- //
- // void Bark() const
- // {
- // cout << "Whaf! " << endl;
- // }
- //};
- //
- //void MakeSound(const Cat& c)
- //{
- // c.Meow();
- //}
- //
- //void MakeSound(const Dog& d)
- //{
- // d.Bark();
- //}
- //
- //int main()
- //{
- // Cat c;
- // Dog d;
- // c.Eat("apple");
- // d.Eat("orange");
- //
- // MakeSound(c);
- // MakeSound(d);
- //
- // return 0;
- //}
- Из базового класса мы не можем добраться до приватных полей классов потомков.
- Иначе это нарушало бы инкапсуляцию (т.е сокрытие данных) и детали внутренней реализации.
- #include <iostream>
- using namespace std;
- class Animal
- {
- public:
- Animal(const string& type):type_(type){}
- void Eat(const string& fruit)
- {
- cout<<type_<<" eats "<<fruit<<endl;
- }
- void Voice() const
- {
- if(type_=="cat")
- {
- cout << "Meow! " << endl;
- }
- else if(type_=="dog")
- {
- cout << "Whaf! " << endl;
- }
- else if(type_=="parrot")
- {
- cout << name_<<" is good!"<<endl;
- }
- }
- private:
- const string type_;
- };
- class Cat : public Animal
- {
- public:
- Cat():Animal("cat"){}
- };
- class Dog : public Animal
- {
- public:
- Dog():Animal("dog"){}
- };
- class Parrot:public Animal
- {
- public:
- Parrot(const string& name):Animal("parrot"),name_(name){}
- // void Talk()
- // {
- // cout<<name_<<" is good!"<<endl;
- // }
- private:
- const string& name_;
- };
- void MakeSound(const Animal& a)
- {
- a.Voice();
- }
- int main()
- {
- Cat c;
- Dog d;
- c.Eat("apple");
- d.Eat("orange");
- MakeSound(c);
- MakeSound(d);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement