码迷,mamicode.com
首页 > 编程语言 > 详细

C++ static member functions

时间:2015-04-18 12:44:37      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:

今天复习老师昨天讲的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我的时间。。。自己还是太年轻了。。

 

C++ static member functions

标签:

原文地址:http://www.cnblogs.com/puorc/p/4437087.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!