程序设计与算法(三)第06周测验

001:看上去像多态

#include 
using namespace std;
class B {
	private:
		int nBVal;
	public:
		void Print()
		{ cout << "nBVal="<< nBVal << endl; }
		void Fun()
		{cout << "B::Fun" << endl; }
		B ( int n ) { nBVal = n;}
};
class D:public B
{
    private:
		int nDVal;
	public:
		void Print()
		{ B::Print();cout << "nDVal="<< nDVal << endl; }
		void Fun()
		{cout << "D::Fun" << endl; }
		D ( int n ):B(3*n) { nDVal = n;}
};
int main() {
	B * pb; D * pd;
	D d(4); d.Fun();//D::Fun
	pb = new B(2); pd = new D(8);
	pb -> Fun(); pd->Fun();//B::Fun D::Fun
	pb->Print (); pd->Print ();//nBVal=2 nBVal=24 nDVal=8
	pb = & d; pb->Fun();//B::Fun
	pb->Print();//nBVal=12
	return 0;
}

002:Fun和Do

#include 
using namespace std;
class A {
	private:
	int nVal;
	public:
	void Fun()
	{ cout << "A::Fun" << endl; };
	void Do()
	{ cout << "A::Do" << endl; }
};
class B:public A {
	public:
	virtual void Do()
	{ cout << "B::Do" << endl;}
};
class C:public B {
	public:
	void Do( )
	{ cout <<"C::Do"<<endl; }
	void Fun()
	{ cout << "C::Fun" << endl; }
};
void Call(B & p) {//Do函数会因为多态而调用C的,Fun函数因为B没有只能调用B的基类A的
	p.Fun(); p.Do();
}
int main() {
	C c;
	Call( c);
	return 0;
}

003:这是什么鬼delete

#include 
using namespace std;
class A
{
public:
	A() { }
	//课程原话,通过基类指针删除派生类对象时,通常只调用基类的析构函数
	//此时的解决办法就是把基类的析构函数声明为虚函数
	virtual ~A(){cout << "destructor A" << endl;}
};
class B:public A {
	public:
	~B() { cout << "destructor B" << endl; }
};
int main()
{
	A * pa;
	pa = new B;
	delete pa;
	return 0;
}

004:怎么又是Fun和Do

#include 
using namespace std;
class A {
	private:
	int nVal;
	public:
	void Fun()
	{ cout << "A::Fun" << endl; };
	virtual void Do()
	{ cout << "A::Do" << endl; }
};
class B:public A {
	public:
	virtual void Do()
	{ cout << "B::Do" << endl;}
};
class C:public B {
	public:
	void Do( )
	{ cout <<"C::Do"<<endl; }
	void Fun()
	{ cout << "C::Fun" << endl; }
};
void Call(A * p) {
	p->Fun(); p->Do();
}
int main() {
	Call( new A());
	Call( new C());
	return 0;
}

你可能感兴趣的:(C++学习)