所以我最近发现它使用了特别的技术我从来没有见过的一些源代码(成语);简而言之;而不是为有问题的类使用静态变量,它使用类源文件中的局部变量。隐藏“静态”类变量
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