标签:小代码
#include"sts.h" #if(0) class Base { public: void f(int x){cout<<"Base::f(int)"<<x<<endl;} void f(float x){cout<<"Base::f(float)"<<x<<endl;} //成员函数重载特征:相同的名字和范围,参数不同virtual关键字可有可无 virtual void g(void){cout<<"Base::g(void)"<<endl;} }; class Derived:public Base { public: virtual void g(void){cout<<"Drived::g(void)"<<endl;} //覆盖不同的范围参数名字均相同,必须要有virtual关键字 }; int main() { Derived d; Base *pb=&d; pb->f(42); //Base::f(int)42 pb->f(4.2f); //Base::f(float)4.2 pb->g(); //Drived::g(void) return 0; } #endif #if(0) class Base2 { public: virtual void f(float x){cout<<"B::f(float)"<<x<<endl;} void g(float x){cout<<"B::g(float)"<<x<<endl;} void h(float x){cout<<"B::h(float)"<<x<<endl;} }; class Derived:public Base2 { public: virtual void f(float x){cout<<"D::f(float)"<<x<<endl;}//覆盖 void g(float x){cout<<"D::g(float)"<<x<<endl;}//隐藏 void h(float x){cout<<"D::h(float)"<<x<<endl;}//隐藏 }; int main() { Derived d; Base2 *pb=&d; Derived *pd=&d; pb->f(1.1f); pd->f(2.2f); pb->g(3.3f); pd->g(4.4f); pb->h(5.5f); pd->h(6.6f); /* D::f(float)1.1 D::f(float)2.2 B::g(float)3.3 D::g(float)4.4 B::h(float)5.5 D::h(float)6.6 */ return 0; } #endif #if(0) class b { public:void f(int x);}; //class d:public b{public:void f(char *str);}; class d:public b{public:void f(char *str);void f(int x){b::f(x);}}; void test(void){d *pd=new d;pd->f(10);}/*编译报错*/ int main() { cout<<"wzzx"<<endl; test(); // 修改class b不同结果 return 0; } #endif #if(0) //声明 可有缺省 从后往前依次缺省 缺省仅书写简单,函数易用 void out(int x); void out(int x,float y=0.0);// //定义 不可有缺省 void out(int x){cout<<"out int "<<x<<endl;} void out(int x,float y){cout<<"out int and float "<<x<<y<<endl;} int main() { cout<<"wzzx"<<endl; int x=1;float y=1.234; //out(x); // is ambiguous,产生二义性 out(x,y); return 0; } #endif #if(0) #define max1(a,b) (a)>(b)?(a):(b) #define max2(a,b) ((a)>(b)?(a):(b)) int main() { int x=1;int y=2; cout<<(max1(x,y)+2)<<endl; //(x)>(y)?(x):(y)+2 cout<<(max2(x,y)+2)<<endl; //(x)>(y)?(x):(y)+2 cout<<(max1(x++,y)+2)<<endl; //(x)>(y)?(x):(y)+2 cout<<(max2(x++,y)+2)<<endl; return 0; } #endif // 内联 不能出现在长函数和循环函数前 #if(0) class b{public:virtual ~b(){cout<<"~b"<<endl;}}; class d:public b{public:virtual ~d(){cout<<"~d"<<endl;}}; int main() { b *pb=new d; delete pb; //~d //~b return 0; } #endif #if(1) /* class string { public: string(const char *str=NULL); string(const string & other); ~string(void); string &operate =(const string & other); private: char *m_data; }; string::string(const char *str) { if(str==NULL){m_data=new char[1];*m_data=‘\0‘;} else {int length =strlen(str);m_data=new char[length+1];strcpy(m_data,str);} } string::~string(void){delete [] m_data;} */ int main() { //9.6----9.7 return 0; } #endif #if(0) #endif
标签:小代码
原文地址:http://sts609.blog.51cto.com/11227442/1749391