|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 红莲教主 于 2016-5-12 10:37 编辑
笔记:重载方法是在一个类中,覆盖发生在基类和子类之间
问题:看不懂
F:\Q\方法覆盖和方法重载\main.cpp|86|warning: deleting object of polymorphic class type 'Animal' which has non-virtual destructor might cause undefined behaviour [-Wdelete-non-virtual-dtor]|
找到解决办法了,就是把Animal类的析构函数变为virtual ~Animal();
- #include <iostream>
- #include <string>
- using std::cout;
- using std::endl;
- using std::string;
- class Animal
- {
- public:
- Animal(string name);
- ~Animal();
- void eat(); //用来测试重载
- void eat(string food); //用来测试重载
- void say(); //用来测试覆盖
- virtual void run(); //用来测试覆盖
- private:
- string name ;
- };
- Animal::Animal(string name)
- {
- this->name = name ;
- }
- Animal::~Animal()
- {
- }
- void Animal::eat()
- {
- cout<<"我是个吃货,我正在吃东西!"<<endl;
- }
- void Animal::eat(string food)
- {
- cout<<"我在吃"<<food<<endl;
- }
- void Animal::say()
- {
- cout<<"我在跟你打招呼,(*^__^*) 嘻嘻……"<<endl;
- }
- void Animal::run()
- {
- cout<<"我在追着你跑哦,我要咬死你"<<endl;
- }
- class Dog : public Animal
- {
- public:
- Dog(string name);
- ~Dog();
- void say();
- virtual void run(); //此处virtual可以不写,virtual会继承,virtual方法不能再次变为非virtual方法
- };
- Dog::Dog(string name):Animal(name)
- {
- }
- Dog::~Dog()
- {
- }
- void Dog::say()
- {
- cout<<"我在汪汪汪。。。"<<endl;
- }
- void Dog::run()
- {
- cout<<"我跑一会儿,撒一泡尿。。"<<endl;
- }
- int main()
- {
- Animal* dog = new Dog("小白");
- dog->say();
- dog->run();
- dog->eat();
- dog->eat("粑粑");
- delete dog ;
- return 0 ;
- }
复制代码 |
|