2018/2/4
虚方法(virtual way)
1.在以前访问变量的时候,是先建立变量,再将变量的地址赋给了指针,通过指针来访问变量的值
Pig pig1("八戒");
Turtle turtle1("龟龟");
cout << "猪类" << endl;
cout << "这只猪的名字是" << pig1.name << endl;
pig1.eat();
/*方法的重载*/
pig1.eatcount(15);
pig1.drool();
pig1.sleep();
pig1.climb();
cout << "龟类" << endl;
cout << "这只龟的名字是" << endl;
turtle1.eat();
turtle1.drool();
turtle1.sleep();
turtle1.swim();
2.现在可以采用虚方法,(new delete)直接创建某个指针指向新分配的内存块
{
/*使用虚方法new delete 直接建立指针指向分配内存区*/
Animal *pig = new Pig("八戒");
Animal *turtle = new Turtle("龟龟");
cout << "这只猪的名字是" << pig->name << endl;
pig->eatcount(15);
pig->drool();
pig->sleep();
pig->eat();
pig->climb();
cout << "这只龟的名字是" <<turtle->name <<endl;
turtle->drool();
turtle->sleep();
turtle->swim();
turtle->eat();
/*!!删除指针!!*/
delete pig;
delete turtle;
注意
1.使用虚方法时,要注意创建指针后,一定要用delete来删除指针
2.由于C++的编译器采用最优读取代码的原则,所以使用方法的重载和覆盖时,要注意使用visual前缀来使编译器正常编译
/*虚方法*/
/*visual way*/
/*以前访问变量时,是先创建一个变量,变量的地址赋给指着你,可以访问变量所在的位置
采用虚方法(new delete)可以直接创建指针来访问新分配的内存块
注意:
1.使用new创建指针后必须要用delete来删除指针;
2.由于编译器的特殊性,喜欢找最优的编译方式,所以使用虚方法时,对于重载或覆盖的方法要用visual前缀*/
#include<iostream>
#include<stdlib.h>
#include<string>
using namespace std;
class Animal
{
public:
string name;
virtual void eat();
virtual void climb();
/*方法的重载*/
void eatcount(int num);
void sleep();
void drool();
protected:
Animal(string theName);
};
class Pig :public Animal
{
public:
Pig(string theName);
void eat();
void climb();
};
class Turtle :public Animal
{
public:
void swim();
Turtle(string theName);
void eat();
};
Animal::Animal(string theName)
{
name = theName;
}
void Animal::climb()
{
cout << "I am climbing" << endl;
}
void Animal::eat()
{
cout << "I am eatting" << endl;
}
void Animal::sleep()
{
cout << "I am sleeping,Don`t bother me" << endl;
}
void Animal::drool()
{
cout << "HUA HUA HUA。。。。" << endl;
}
void Animal::eatcount(int num)
{
cout << "我吃了" << num << "碗饭" << endl;
}
/*启用猪类构造器*/
Pig::Pig(string theName) :Animal(theName)
{
}
/*方法的覆盖
相当于在子类中重新定义一个方法,该方法继承于基类的方法(Animal::eat()),注意要在子类中重新声明方法*/
void Pig::eat()
{
/*Animal::eat();*/
cout << "I am eatting the meat" << endl;
}
void Pig::climb()
{
cout << "母猪会上树\n" << endl;
}
/*继承构造器*/
Turtle::Turtle(string TheName) :Animal(TheName)
{
}
void Turtle::swim()
{
cout << "总有一天我会超越孙杨\n" << endl;
}
void Turtle::eat()
{
/* Animal::eat();*/
/*方法的覆盖*/
cout << "我要吃鱼" << endl;
}
void main()
{
/*使用虚方法new delete 直接建立指针指向分配内存区*/
Animal *pig = new Pig("八戒");
Turtle *turtle = new Turtle("龟龟");
cout << "这只猪的名字是" << pig->name << endl;
pig->eatcount(15);
pig->drool();
pig->sleep();
pig->eat();
pig->climb();
cout << "这只龟的名字是" <<turtle->name <<endl;
turtle->drool();
turtle->sleep();
turtle->swim();
turtle->eat();
/*!!删除指针!!*/
delete pig;
delete turtle;
system("pause");
}