// static_test.h : 头文件
002 #pragma once
003
004 class static_test
005 {
006 public:
007 static_test();//默认构造函数
008 void set(int x, int y, int z);//成员变量初始化
009 int add();//
010 static int add2();//静态成员函数
011 ~static_test();
012 static int sum;//公有的静态成员变量
013 private:
014 static int sum2;//私有的静态成员变量
015 int a, b, c;
016 };
017
018
019 // static_test.cpp : 定义控制台应用程序的入口点。
020 //
021
022 #include "stdafx.h"
023 #include "static_test.h"
024 #include <iostream>
025 using namespace std;
026
027 /*
028 notice:
029 如果sum,sum2这两个静态成员变量没有在这里定义,就会出现错误:
030 static_test.obj : error LNK2001: 无法解析的外部符号 "private: static int static_test::sum2"
031 static_test.obj : error LNK2001: 无法解析的外部符号 "public: static int static_test::sum"
032 */
033 int static_test::sum = 0; //
034 int static_test::sum2 = 0; //
035
036 /*
037 全局函数可以调用类的public型的静态成员变量sum,可以改变它的值。
038 但不能用sum2,因为sum2是private类型的。
039 */
040 int fun_add(int x, int y, int z)
041 {
042 static_test::sum += x+y+z;
043 return static_test::sum;
044 }
045
046 /*
047 成员变量的初始化
048 */
049 static_test::static_test()
050 {
051 this->a = 0;
052 this->b = 0;
053 this->c = 0;
054 }
055
056 /*
057 给成员变量赋值
058 */
059 void static_test::set(int x, int y, int z)
060 {
061 a = x;
062 b = y;
063 c = z;
064 }
065
066 /*
067 析构函数
068 */
069 static_test::~static_test(void)
070 {
071 }
072
073 /*
074 成员函数的实现
075 */
076 int static_test::add()
077 {
078 return a+b+c;
079 }
080
081 /*
082 静态成员函数的实现
083 注意:静态成员函数只能访问类的静态成员变量。
084 定义时,前面不能加static,否则出现error C2724: “static_test::add2”: “static”不应在文件范围内定义的成员函数上使用错误:
085 */
086 int static_test::add2()
087 {
088 return sum2;
089 }
090
091 int _tmain(int argc, _TCHAR* argv[])
092 {
093 int result = 0; //保存结果
094 static_test test;//创建一个对象
095 test.set(1, 2, 3);
096 result = test.add();
097 cout<<result<<endl;//result = 6
098 result = fun_add(4, 5, 6);
099 cout<<result<<endl;//result = 15
100 result = fun_add(1, 2, 3);
101 cout<<result<<endl;//result = 21 因为sum为静态成员变量,该变量的值可以保存给下一次调用,而不会冲掉,直到程序结束为止。
102 return 0;
103 }
转载自:http://www.oschina.net/code/snippet_160829_5854