|
1、#include <stdio.h> class A{ public: A(){func(0);}; virtual void func(int data){printf("A1 :%d",data);} virtual void func(int data) const{printf("A2 :%d",data);} void func(char *str){printf("A3 :(%s)",str);} }; class B:public A{ public: void func(){printf("B1 :%s","");} void func(int data){printf("B2 :%d",data);} void func(char *str){printf("B3 :(%s)",str);} }; int main() { A *pA; B b; const A *pcA; pA=&b; pA->func(1); pA->func("test"); A().func(1); pcA=&b; pcA->func(2); return 0; } 程序运行的结果: A1 :0 B2 :1 A3 :(test) A1 :0 A1 :1 A2 :2 1) 基类的指针指向派生类对象:那么该指针只能够调用基类所定义的函数,但是如果该函数为虚函数,则调用该派生类自己的成员函数。(B2 :1) 2) 如果以派生类的指针指向基类对象,则必须事先做明显的转型操作,但是这种做法很危险。 2、
template <typename T> void func(const int &t) { cout<<t+100<<endl; } template<typename T> void func(const T&t) { cout<<t<<endl; } int main() { func(10.3); func(1000); return 0; } 程序运行结果: 10.3 1000 如果上述函数改为
void func(const int &t) { cout<<t+100<<endl; } template<typename T> void func(const T&t) { cout<<t<<endl; } int main() { func(10.3); func(1000); return 0; } 则程序的运行结果为: 10.3 1100 如果使用函数的非模板形式,不能在前面加上template关键字。 3、 改错:
class klass { public: klass(){} private: ~klass(){} void func(int n){ cout<<"klass!!"<<endl; } public: void test(){ func(100); } }; int main() { klass k; k.test(); return 0; } 运行后程序显示:error C2248: 'klass::~klass' : cannot access private member declared in class 'klass' 证明析构函数的属性必须为public。 但是,如果把klass k改为klass* pk; pk=new klass; pk->test();程序通过,但是klass不能释放 |


