• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
一蓑烟雨
C/C++,Linux,语音技术
博客园    首页    新随笔    联系   管理    订阅  订阅
static--静态方法与静态成员

1、Test.h

 1 class Test
 2 {
 3 public:
 4        Test();
 5        virtual ~Test();
 6        virtual void action();
 7        static virtual void go();
 8 private:
 9        static int mLay;
10        int mOut;
11 
12 };

此处,static 与 virtual不能共用,此时这里去掉virtual关键字。

2、Test.h

 1 class Test
 2 {
 3 public:
 4        Test();
 5        virtual ~Test();
 6        virtual void action();
 7        static void go();
 8 private:
 9        static int mLay;
10        int mOut;
11 
12 };

Test.cpp

 1 #include <iostream>
 2 #include "Test.h"
 3 
 4 using namespace std;
 5 
 6 Test::Test():mLay(1)
 7 {
 8 }
 9 Test::~Test()
10 {
11 }
12 void Test::action()
13 {
14   mLay++;
15   cout<<mLay<<endl;
16 }

由于mLay是静态数据成员,所以不可以初始化。

而mOut是非静态的,所以可以初始化,如下。

Test.cpp

 1 #include <iostream>
 2 #include "Test.h"
 3 
 4 using namespace std;
 5 
 6 Test::Test():mOut(1)
 7 {
 8 }
 9 Test::~Test()
10 {
11 }
12 void Test::action()
13 {
14   mOut++;
15   cout<<mOut<<endl;
16 }

statictest.cpp

 1 // statictest.cpp : 定义控制台应用程序的入口点。
 2 //
 3 
 4 #include "stdafx.h"
 5 #include "Test.h"
 6 
 7 int _tmain(int argc, _TCHAR* argv[])
 8 {
 9     Test test;
10     test.action();
11     return 0;
12 }

结果为2。

3、Test.cpp

 1 #include <iostream>
 2 #include "Test.h"
 3 
 4 using namespace std;
 5 
 6 Test::Test():mOut(1)
 7 {
 8 }
 9 Test::~Test()
10 {
11 }
12 void Test::action()
13 {
14   mOut++;
15   cout<<mOut<<endl;
16 }
17 void Test::go()
18 {
19   mOut++;
20   cout<<mOut<<endl;
21 }

statictest.cpp

 1 // statictest.cpp : 定义控制台应用程序的入口点。
 2 //
 3 
 4 #include "stdafx.h"
 5 #include "Test.h"
 6 
 7 int _tmain(int argc, _TCHAR* argv[])
 8 {
 9     Test test;
10     test.go();
11     return 0;
12 }

生成解决方案有问题,说明静态方法不可以访问非静态成员。

posted on 2012-08-16 10:00  lovemu  阅读(351)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3