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 }
生成解决方案有问题,说明静态方法不可以访问非静态成员。