////////////// //fileName:TestClass.h //////////// //#pragma once #ifndef THIS___ #define THIS___ #include <iostream> using namespace std; //const int TestClass::m_con_var class TestClass { public: TestClass(); TestClass(int n); virtual ~TestClass(void); int m_ntestVar; static int m_nvar; const static int m_cnsta_var; static const int m_con_var ; private: public: int display(void); }; //const int TestClass::m_con_var; #endif ////////////// //fileName:TestClass.cpp //////////// #include "TestClass.h" TestClass::TestClass(){ } TestClass::TestClass(int n):m_ntestVar(n) { cout << "m_nvar" << TestClass::m_nvar << endl; cout << "this->m_ntestVar" << this->m_ntestVar << endl; cout << "m_cnsta_var" << TestClass::m_cnsta_var << endl; TestClass::m_nvar++; } TestClass::~TestClass(void) { cout << TestClass::m_nvar << endl; } // demo_static.cpp : Defines the entry point for the console application. // #include "TestClass.h" //static const int TestClass::m_con_var; //int TestClass::m_nvar = 0; //int TestClass::m_cnsta_var = 12; //TestClass::m_ntestVar //extern const int m_con_var; /*int TestClass::m_con_var = 0*/; int TestClass::m_nvar; const int TestClass::m_cnsta_var = 0; const int TestClass::m_con_var = 0; int main(int argc, char * argv[]) { TestClass tc(10); TestClass tc1(120); TestClass tcc[100]; int i = 0; while(i < 100){ tcc[i] = TestClass(0); i++; } return 0; }
const static 和static const成员在类体中只有声明,在实现文件TestClass.cpp中也没有定义,却把定义放到了main函数所在的文件中。不解??这个程序也一个做游戏的朋友告诉我的,还没呢理解,先放到这里。
执行结果与
一样: