从0学习C++ (九) 构造函数

#include <iostream>;
using namespace std;


/*
	类继承中的构造函数
	当Animal的构造函数变为Animal(int height,int weight)时,系统并不会为Animal生成默认构造函数。
	这个时候 Fish类的构造函数要变为:Fish(): Animal(100,200) --》其中的100 200为传入的参数。
	Fish类可以在构造的时候为常量 a 赋值。 Fish(): Animal(100,200),a(1) 其中1是给常量赋的值
	~Animal(){}  析构函数。 释放对象。
*/
class Animal
{
public:
	/*Animal()
	{
		cout << "Animal construct" << endl;
	}*/
	Animal(int height,int weight)
	{
		cout << "Animal construct" << endl;
	}

	~Animal()
	{
		cout << "Animal deconstruct" << endl;
	}

	void eat()
	{
		cout << "Animal eat" << endl;
	}

	void sleep()
	{
		cout << "Animal sleep" << endl;
	}

	//虚函数
	virtual void breathe()
	{
		cout << "Animal breathe" << endl;
	}

	
};


class Fish : public Animal
{
private :
	const int a;

public :
	//在构造函数中给常量赋值。
	Fish(): Animal(100,200),a(1)
	{
		cout << "Fish construct" << endl;
	}

	~Fish()
	{
		cout << "Fish deconstruct" << endl;
	}

	void breathe()
	{
		cout << "fish bubble" << endl;
	}

	
};

  
  
  
int main(){ 

	Fish fish;
	
	return 0 ;
}  


运行截图:
[img]

[/img]

猜你喜欢

转载自android-zhang.iteye.com/blog/2000443