1、不创建对象调用类的成员函数,该调用不能需构造函数初始化的变量。
为什么C++可以这么调用:因为经编译器编译过后的成员函数类似普通的非成员函数,不像成员变量创建多次需要多次分配空间,所以成员函数能调,有成员变量的就不行了。
二、待续。。。代码示例:
#include <iostream> using namespace std; class Test { public: Test(){ cout<<"\nconstruction of Test!"<<endl; m_nValue = m_nValue2 = -1; } void fun(){ cout<< "fun():\t"; cout<< m_nValue<<endl; } void fun2(){ cout<< m_nValue2<<endl; //error!,m_nValue2 doesn't defined; } private: static int m_nValue; int m_nValue2; }; int Test::m_nValue = 10; int main() { ((Test*)0)->fun(); //该方法调用函数的输出变量针对静态变量,已初始化 cout<< "it's just a test!..."<<endl; Test test; return 0; }
测试结果: