開發平台(Platform): (Ex: Win10, Linux, ...)
windows11
編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出)
Visual Studio 2022
有兩個矩形 class
其中算周長的函式
一個是用一般成員函式
另一個是用靜態成員函式
但這個靜態成員函式的用法我是第一次看到
只要把物件自己的指標傳進去
靜態成員函式就可以使用 private 的一般成員變數了耶!!
連 Get 函式都可以不用
根本就跟一般成員函式一樣
C++ 程式碼如下:
class Rectangle01
{
private:
int width;
int height;
public:
Rectangle01(int width, int height) {
this->width = width;
this->height = height;}
int Perimeter() { return width * 2 + height * 2;}
};
class Rectangle02
{
private:
int width;
int height;
public:
Rectangle02(int width, int height) {
this->width = width;
this->height = height;}
static int Perimeter(Rectangle02 *pRec02) {
return pRec02->width * 2 + pRec02->height * 2; }
};
int main()
{
Rectangle01 *pRec01 = new Rectangle01(10, 20);
cout << pRec01->Perimeter() << endl;//60
Rectangle02 *pRec02_1 = new Rectangle02(100, 200);
cout << Rectangle02::Perimeter(pRec02_1) << endl;//600
Rectangle02 *pRec02_2 = new Rectangle02(200, 300);
cout << Rectangle02::Perimeter(pRec02_2) << endl;//1000
delete pRec01;
delete pRec02_1;
delete pRec02_2;
system("pause");
return 0;
}
我知道靜態成員函式只能存取靜態成員變數
不需要 new 出物件也能被呼叫
所以不能用 this
也不能存取一般成員變數
講到靜態成員函式
查資料都說是都說是獨立於物件之外配置的記憶體空間
不管 new 出幾個物件
都是「使用同一個記憶體空間」
也就說靜態成員函式比一般成員函式省空間(嗎?)
另外我也測量過執行時間
迴圈1千萬次執行 new、呼叫 Perimeter 函式、delete
程式各執行10次的平均值
Rectangle01 是 2607.129 ms
Rectangle02 是 2709.032 ms
沒有差很多
問題一
時間上沒有差很多
但如果真能省空間
把所有的一般成員函式通通改成靜態的
超省空間的是不是!!
講得我都想買了
那為什麼沒看見有人這樣做呢?
是會有其他什麼潛在的問題嗎?
問題二
前面提過
靜態成員函式是獨立於物件之外配置的記憶體空間
不管 new 出幾個物件
都是「使用同一個記憶體空間」
所以真的會比一般成員函式省空間嗎?
要怎麼看出物件占多少空間這件事?
先說我自己是沒有這樣用過
只是研究 static 的時候發現了這種用法
所以來請問大家的看法