C++测验小结3

  • 编程填空:统计动物数量

描述

代码填空,使得程序能够自动统计当前各种动物的数量

#include <iostream>
using namespace std;

// 在此处补充你的代码


void print() {
	cout << Animal::number << " animals in the zoo, " 
         << Dog::number << " of them are dogs, " 
         << Cat::number << " of them are cats" << endl;
}

int main() {
	print();
	Dog d1, d2;
	Cat c1;
	print();
	Dog* d3 = new Dog();
	Animal* c2 = new Cat;
	Cat* c3 = new Cat;
	print();
	delete c3;
	delete c2;
	delete d3;
	print();
}

输入

输出

0 animals in the zoo, 0 of them are dogs, 0 of them are cats
3 animals in the zoo, 2 of them are dogs, 1 of them are cats
6 animals in the zoo, 3 of them are dogs, 3 of them are cats
3 animals in the zoo, 2 of them are dogs, 1 of them are cats

分析:主要考查静态成员变量和派生。从输出我们就可以发现,animal的数量完全是随着dog和cat的数量而变化的,它应该是只有一份的,即animal、dog、cat的number都应该是静态的,全局的,并且应初始化为0;还会发现输出第二行dog的数量变为2完全是因为生成了两个dog对象,自然想到在Dog类的构造函数内必然要执行将dog的number加一的操作,同时在其析构函数中会执行数量减一的操作,cat同理即可。

最后需注意的是,在Animal的析构函数前应该加上vitual关键字,构成虚析构函数,为了让继承它的两个子类的析构函数起作用。

代码如下:

#include <iostream>
using namespace std;

class Animal
{
public:
	static int number;
	Animal() {
		number++;
	}
	virtual ~Animal() {
		//如果不加virtual,
		//删除c2的时候就不能调用Cat的析构函数了 这里是虚析构函数,
		//为了让继承它的两个子类的析构函数起作用
		number--;
	}
};
class Dog :public Animal
{
public:
	static int number;
	Dog() {
		++number;
	}
	~Dog() {
		--number;
	}
};
class Cat :public Animal
{
public:
	static int number;
	Cat() {
		++number;
	}
	~Cat() {
		--number;
	}
};
int Animal::number = 0;
int Dog::number = 0;
int Cat::number = 0;
void print() {
	cout << Animal::number << " animals in the zoo, " 
		<< Dog::number << " of them are dogs, " 
		<< Cat::number << " of them are cats" << endl;
}
int main() {
	print();
	Dog d1, d2;
	Cat c1;
	print();
	Dog* d3 = new Dog();
	Animal* c2 = new Cat;
	Cat* c3 = new Cat;
	print();
	delete c3;
	delete c2;
	delete d3;
	print();
}
  • 这个指针哪来的

填空,按要求输出

#include <iostream>
using namespace std;

struct A
{
	int v;
	A(int vv):v(vv) { }

// 在此处补充你的代码


};

int main()
{
	const A a(10);
	const A * p = a.getPointer();
	cout << p->v << endl;
	return 0;
}

输入

输出

10

分析:主要考查常量成员函数。观察主函数,我们可以发现定义的对象a是const的,而下面的成员函数getPointer必然应该是常量的,而函数的返回值是一个常量的指针,所以我们只需要返回这个常量指针就?了。

代码如下:

#include <iostream>
using namespace std;

struct A
{
	int v;
	A(int vv) :v(vv) { }
	const A* getPointer() const{
		return this;
	}
};

int main()
{
	const A a(10);   //常量对象只能使用构造函数、析构函数和有const说明符的函数
	const A * p = a.getPointer();
	cout << p->v << endl;
	return 0;
}

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值