(1)使用静态成员函数.改好(我现在正无聊)
#include <iostream>
using namespace std;
#include<string.h>
class person{
public:
char m_strName[20];
static long m_ID;
public:
person(char*strName,long ID){strcpy(m_strName, strName);m_ID=ID;}
static long GetID() {return m_ID;}
};
long person::m_ID;
void main ()
{
person personl ("LiuJun",1101640524);
cout<<"ID="<<person::GetID()<<'\n';
}
(2)派生类的构造函数调用基类的构造函数。
#include <iostream>
using namespace std;
class point
{
protected:
int x,y;
public:
point(int a ,int b){x=a;y=b;}
int getX(){return x;}
int getY(){return y;}
};
class Circle :public point
{
protected:
int radius;
public:
Circle(int a=0,int b=0,int r=0) : point(a, b) {radius=r;}
int getRadius() {return radius;}
};
void main()
{
Circle c(100,150,200);
cout<<"x="<<static_cast<point>(c).getX()<<",y="<<static_cast<point>(c).getY()<<", radius="<<c.getRadius()<<endl;
}
(3)关于常对象和常对象成员。
#include <iostream>
using namespace std;
class Sample
{
private:
int n;
public:
Sample(int x){n=x;}
void SetValue(int x){n=x;}
void Display(){cout<<"n="<<n<<endl;}
};
void main()
{
const Sample * a = new Sample(100);
const_cast<Sample*>(a)->SetValue(0);
const_cast<Sample*>(a)->Display();
delete a;
}