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; }
测试结果:
C++静态成员与非静态成员调用
本文探讨了C++中不通过创建对象直接调用类成员函数的情况,特别是针对静态成员与非静态成员的区别。通过示例代码解释了为何可以直接调用静态成员函数而不能直接调用需要构造初始化的非静态成员函数。

1777

被折叠的 条评论
为什么被折叠?



