023:看上去像多态
#include <iostream>
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();
pb = new B(2); pd = new D(8);
pb -> Fun(); pd->Fun();
pb->Print (); pd->Print ();
pb = & d; pb->Fun(); //不是多态,静态编译,调用基类的Fun()和Print()
pb->Print();
system("pause");
return 0;
}
我开始不知道怎么写是没有想到还可以在写派生类的构造函数时通过初始化列表时改变基类变量值。
24 Fun和Do
#include <iostream>
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 ) {
p.Fun(); p.Do();
}
int main() {
C c;
Call( c);
system("pause");
return 0;
}
如果Call()里面的参数写的是A & p,由于A类里面没有声明Virtual,所以结果都是调用A的Fun()和Do()
025:这是什么鬼delete
#include <iostream>
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;
system("pause");
return 0;
}
026:怎么又是Fun和Do
#include <iostream>
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());
system("pause");
return 0;
}
这题与之前那题不同之处在于调用Call(new A())函数时参数是基类A的指针,因此在定义Call()函数时参数不能写成B *p,原因是不能将基类指针赋值给派生类指针(即派生类指针不能指向基类对象),但是反过来可以。