所以我最近發現它使用了特別的技術我從來沒有見過的一些源代碼(成語);簡而言之;而不是爲有問題的類使用靜態變量,它使用類源文件中的局部變量。隱藏「靜態」類變量
myclass.h
class myclass {
//static int myint;
public:
myclass();
~myclass();
int count();
};
myclass.cpp
#include "myclass.h"
int myint = 0;
myclass::myclass() {
myint++;
}
myclass::~myclass() {
myint--;
}
int myclass::count() {
return myint;
}
的main.cpp
#include "myclass.h"
#include <iostream>
int main() {
myclass aclass;
myclass theclass;
std::cout << theclass.count(); //outputs 2
return 0;
}
我的問題是,爲什麼會有人採取這種方法比使用一個靜態變量?
我的看法是,由於變量只能被myclass類(private static)知道,並且繼承並不重要(在這種情況下),這可能會阻止其他人知道這個變量。但那是我能看到的唯一優勢;不知道這是否值得。
同樣的問題也適用於(靜止/非 - 靜態)是私有成員函數;當繼承不重要時。
編輯:閱讀後左右,我打算做一個刺,這是因爲有些人還在用C編程風格...
+1使用無名命名空間,作爲[靜態]的[高級替代](http://stackoverflow.com/questions/4422507/superiority-of-unnamed-namespace-over-static)。 – Nawaz 2011-02-12 08:48:03
值得一提的是,大多數在線C++教程在技術上不正確,或者提倡窮人的風格。 (真的很傷心,真的......) – 2011-02-12 08:50:58