今天复习老师昨天讲的static member functions。总觉得这玩意儿存在真是莫名其妙,度娘之,发现网上讲的都十分不清楚。还是用Google从米国网站找到了答案。
class Something { private: static int s_nValue; }; int Something::s_nValue = 1; // initializer int main() { // how do we access Something::s_nValue? }
In this case, we can‘t access Something::s_nValue directly from main(), because it is private. Normally we access private members through public member functions. While we could create a normal public member function to access s_nValue, we‘d then need to instantiate an object of the class type to use the function! We can do better. In this case, the answer to the problem is that we can also make member functions static.
Like static member variables, static member functions are not attached to any particular object. Here is the above example with a static member function accessor:
class Something { private: static int s_nValue; public: static int GetValue() { return s_nValue; } }; int Something::s_nValue = 1; // initializer int main() { std::cout << Something::GetValue() << std::endl; }
以上来自http://www.learncpp.com/cpp-tutorial/812-static-member-functions/
所以说,static member functions纯属是为了避免访问私有static变量再新建对象调用方法修改值的麻烦。
但我记得老师说static还可以通过对象来修改非static的值。用以下代码测试了下
#include <iostream> using namespace std; class StaticFunction{ public:static int y; int z; static void operate(int x){ y = x; }; static void operate(StaticFunction M, int x){ M.z= x; } }; int StaticFunction::y = 0; int main(){ StaticFunction::operate(5); cout << StaticFunction::y << endl; StaticFunction example; StaticFunction::operate(example, 6); cout << example.z << endl; cin.get(); }
结果每次VS2013都提示z未初始化。开始还以为是没有拷贝构函的缘故,又是写构函,又是新建类,折腾了半天还是没有解决问题。最后,终于—
static void operate(StaticFunction M, int x){ M.z= x; }
这明明就和example的值没什么关系,在M前面加了个麻花(&),问题解决。。。TAT我的时间。。。自己还是太年轻了。。