|
珞珈山水BBS →
电脑网络 →
程序人生 →
单文区文章阅读
|
| 单文区文章阅读 [返回] |
|---|
|
发信人: awded (没有追求了), 信区: Programm 标 题: Re: 静态成员函数不可访问所在类的非静态成员的原因 发信站: 珞珈山水BBS站 (Mon Apr 25 18:52:58 2005), 转信 #include <iostream> #include <stdlib.h> using namespace std; class TestStatic { private: static int s_i;//static int m_i;//member variable public: TestStatic():m_i(2) { } /** * 静态函数,可以操作静态变量,而无法操作成员变量 */ static int GetI() { /* * wrong! * s_i = m_i; */ return TestStatic::s_i; } /** * 非静态函数,可以操作静态变量也可以操作成员变量 */ void SetI() { TestStatic::s_i = m_i; } }; /*定义,只能定义一次。在DEV-CPP中有可能出错,但在 *Visual Studio 中正常,GCC中亦正常。 *在官方文件中,应该如此定义,初步估计应该是DEV-CPP中的一个Bug *DEV-CPP 4.9.9.0,采用GCC3.3.1 */ int TestStatic::s_i = 0; int main(int argc, char *argv[]) { TestStatic obj; cout << obj.GetI() << endl;//can do with it cout << TestStatic::GetI() << endl;//also can do with it obj.SetI(); cout << obj.GetI() << endl; system("PAUSE"); return 0; } 【 在 crescentup (只谈C++) 的大作中提到: 】 : 能不能给个示例? : 谢谢! -- ※ 来源:·珞珈山水BBS站 bbs.whu.edu.cn·[FROM: 222.20.198.*] |
| [返回单文区目录] |
|
|