今天编写了一个简单得VC程序,主要是熟悉一下VC中文件的组织格式及VC中的一些相关知识点.
程序内容介绍:
编写了一个父类Animal,定义了Breath、Eat等方法和Life属性;接下来编写了Animal的子类Fish,在继承父类方法的同时有定义了自己的方法Swim。
文件主要包括:Animal.h、Fish.h、Animal.cpp、Fish.cpp和Main.cpp。
主要内容如下:
<1>Animal.h
****************************************************
#ifndef ANIMAL_H_H
#define ANIMAL_H_H
class Animal
{
public:
int Life;
Animal();
Animal(int);
void Breath();
void Eat();
~Animal();
};
#endif
****************************************************
<2>Animal.cpp
****************************************************
#include "Animal.h"
#include <iostream.h>
Animal::Animal()
{
Animal::Life=0;
cout<<"Animal whose life is 0 has been constructed! "<<endl;
}
Animal::Animal(int x)
{
Animal::Life=x;
cout<<"Animal whose life is "<<Animal::Life<<"has been constructed!"<<endl;
}
void Animal::Breath()
{
cout<<"Animal is breathing..."<<endl;
}
void Animal::Eat()
{
cout<<"Animal is eatting..."<<endl;
}
Animal::~Animal()
{
cout<<"Animal has been deconstructed!"<<endl;
}
****************************************************
<3>Fish.h
****************************************************
#include "Animal.h"
#ifndef FISH_H_H
#define FISH_H_H
class Fish : public Animal
{
public:
Fish();
void Breath();
void Swim();
~Fish();
};
#endif
****************************************************
<4>Fish.cpp
****************************************************
#include "Fish.h"
#include "Animal.h"
#include<iostream.h>
Fish::Fish():Animal(5)
{
cout<<"Fish whose life is "<<this->Life<<" has been constructed!"<<endl;
}
void Fish::Swim()
{
cout<<"Fish is swimming..."<<endl;
}
void Fish::Breath()
{
cout<<"Fish is bubbling..."<<endl;
}
Fish::~Fish()
{
cout<<"Fish has been destructed!"<<endl;
}
****************************************************
<5>Main.cpp
****************************************************
#include "Animal.h"
#include "Fish.h"
#include <iostream.h>
void fn(Animal & x)
{
x.Breath();
}
void main()
{
Fish fh;
fh.Swim();
fh.Breath();
Animal &an=fh;
fn(an);
return;
}
****************************************************
主要知识点:文件预处理<目的:避免重复定义>的使用及原理、类的继承、指针同引用的区别、构造函数与析构函数的调用顺序、变量的存储空间原理<Eg:为何可以把Fish对象赋给一个Animal对象?
推广:学习一下结构体和类的区别<在于访问控制方面>和联系,虚函数的使用及目的<延迟编译>,函数的覆盖问题,各种不同继承<Public、Protected、Private>的区别,VC++程序编译链接的过程等。