---
title: "从0学习C++ (九) 构造函数"
author: "android_zhang"
date: "2014-01-07T17:03:34Z"
tags: []
categories: ["移动开发"]
slug: "0-c"
draft: false
lastmod: "2014-01-07T17:03:34Z"
id: 2000443
url: "https://android-zhang.iteye.com/blog/2000443"
---

```java
#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 ;
}  

```


运行截图：

![](http://dl2.iteye.com/upload/attachment/0092/9027/da291f84-1bbc-31f3-9f79-31ae392c4d3a.png)