c++ 指向类的静态成员的指针
生活随笔
收集整理的這篇文章主要介紹了
c++ 指向类的静态成员的指针
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
- 對類的靜態成員的訪問不依賴于對象
- 可以用普通的指針來指向和訪問靜態成員
using namespace std;
class point
{
? ? public:
? ? ? ? point(int xx=0, int yy=0)
? ? ? ? {
? ? ? ? ? ? X ? = xx;
? ? ? ? ? ? Y ? = yy;
? ? ? ? ? ? countP++;
? ? ? ? }
? ? ? ? point(point &p); ? ?//拷貝構造函數
? ? ? ? int getX()
? ? ? ? {
? ? ? ? ? ? return X;
? ? ? ? }
? ? ? ? int getY()
? ? ? ? {
? ? ? ? ? ? return Y;
? ? ? ? }
? ? ? ? static int countP;
? ? private:
? ? ? ? int X, Y;
};
point::point(point &p)
{
? ? X ? = p.X;
? ? Y ? = p.Y;
? ? countP++;
}
int point::countP=0; ? ?//靜態數據成員定義性說明
int main()
{
? ? //聲明一個int型指針,指向類的靜態成員
? ? int *count ?= &point::countP;
? ? point A(5, 6);
? ? cout << "point A, " << A.getX() << " ," << A.getY() << endl;
? ? //直接通過指針訪問靜態數據成員
? ? cout << "object id = " << *count << endl;
? ? point B(A); //聲明對象B
? ? cout << "point B, " << B.getX() << " ," << B.getY() << endl;
? ? //直接通過指針訪問靜態數據成員
? ? cout << "object id = " << *count << endl;
? ? return 0;
}
例二: #include <iostream>
using namespace std;
class Point
{
? ? public:
? ? ? ? static void getC() ?// <== 靜態函數成員
? ? ? ? {
? ? ? ? ? ? cout << "object id = " << countP << endl;
? ? ? ? }
? ? ? ? Point(int x, int y)
? ? ? ? {
? ? ? ? ? ? X ? = x;
? ? ? ? ? ? Y ? = y;
? ? ? ? }
? ? ? ? int getX()
? ? ? ? {
? ? ? ? ? ? return X;
? ? ? ? }
? ? ? ? int getY()
? ? ? ? {
? ? ? ? ? ? return Y;
? ? ? ? }
? ? ? ? Point(Point &p);
? ? private:
? ? ? ? int X, Y;
? ? ? ? static int countP; ?// <== 靜態成員變量,引用性說明
};
Point::Point(Point &p)
{
? ? X ? = p.X;
? ? Y ? = p.Y;
? ? countP++;
}
int Point::countP ? = 0; ? ?// <== 靜態數據成員定義性說明
int main()
{
? ? void (*gc)() ? ?= Point::getC;
? ? Point A(5, 8);
? ? cout << "Point A, " << A.getX() << ", " << A.getY() << endl;
? ? (*gc)(); ? ? ? ? ? ? ? ?// <=== 打印出來靜態成員的值
? ? Point B(A);
? ? cout << "Point B, " << B.getX() << ", " << B.getY() << endl;
? ? return 0;
}
總結
以上是生活随笔為你收集整理的c++ 指向类的静态成员的指针的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql profiling 应用
- 下一篇: c++ 深复制