用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - c++代码库

c++ 在派生类重载的构造函数

2012-11-26 作者: 程序猿style举报

[c++]代码库

#include <iostream>
using namespace std;

enum BREED {
	GOLDEN, CAIRN, DANDIE, SHETLAND, DOBERMAN, LAB
};

class Mammal {
public:
	// constructors
	Mammal();
	Mammal(int age);
	~Mammal();

	//accessors
	int GetAge() const {
		return itsAge;
	}
	void SetAge(int age) {
		itsAge = age;
	}
	int GetWeight() const {
		return itsWeight;
	}
	void SetWeight(int weight) {
		itsWeight = weight;
	}

	//Other methods
	void Speak() const {
		cout << "Mammal sound!\n";
	}
	void Sleep() const {
		cout << "shhh. I'm sleeping.\n";
	}

protected:
	int itsAge;
	int itsWeight;
};

class Dog: public Mammal {
public:

	// Constructors
	Dog();
	Dog(int age);
	Dog(int age, int weight);
	Dog(int age, BREED breed);
	Dog(int age, int weight, BREED breed);
	~Dog();

	// Accessors
	BREED GetBreed() const {
		return itsBreed;
	}
	void SetBreed(BREED breed) {
		itsBreed = breed;
	}

	// Other methods
	void WagTail() const {
		cout << "Tail wagging...\n";
	}
	void BegForFood() const {
		cout << "Begging for food...\n";
	}

private:
	BREED itsBreed;
};

Mammal::Mammal() :
		itsAge(1), itsWeight(5) {
	cout << "Mammal constructor..." << endl;
}

Mammal::Mammal(int age) :
		itsAge(age), itsWeight(5) {
	cout << "Mammal(int) constructor..." << endl;
}

Mammal::~Mammal() {
	cout << "Mammal destructor..." << endl;
}

Dog::Dog() :
		Mammal(), itsBreed(GOLDEN) {
	cout << "Dog constructor..." << endl;
}

Dog::Dog(int age) :
		Mammal(age), itsBreed(GOLDEN) {
	cout << "Dog(int) constructor..." << endl;
}

Dog::Dog(int age, int weight) :
		Mammal(age), itsBreed(GOLDEN) {
	itsWeight = weight;
	cout << "Dog(int, int) constructor..." << endl;
}

Dog::Dog(int age, int weight, BREED breed) :
		Mammal(age), itsBreed(breed) {
	itsWeight = weight;
	cout << "Dog(int, int, BREED) constructor..." << endl;
}

Dog::Dog(int age, BREED breed) :
		Mammal(age), itsBreed(breed) {
	cout << "Dog(int, BREED) constructor..." << endl;
}

Dog::~Dog() {
	cout << "Dog destructor..." << endl;
}
int main() {
	Dog Fido;
	Dog rover(5);
	Dog buster(6, 8);
	Dog yorkie(3, GOLDEN);
	Dog dobbie(4, 20, DOBERMAN);
	Fido.Speak();
	rover.WagTail();
	cout << "Yorkie is " << yorkie.GetAge() << " years old" << endl;
	cout << "Dobbie weighs ";
	cout << dobbie.GetWeight() << " pounds" << endl;
	return 0;
}


网友评论    (发表评论)

共1 条评论 1/1页

发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。


扫码下载

加载中,请稍后...

输入口令后可复制整站源码

加载中,请稍后...