c++中使用指针调用函数和使用指针调用类对象的()重载函数


使用函数指针时,指针可以像函数名一样,直接加括号和参数列表调用;也可先解引用再调用

 1 1 //include directories...
 2  2 using namespace std;
 3  3 void testFun()
 4  4 {
 5  5     cout<<"this is a test"<<endl;
 6  6 }
 7  7 int main(int argc,char**argv)
 8  8 {
 9  9     auto *pFun=testFun;
10 10     pFun();//or (*pFun)() is also fine   
11 11 }

但是使用类指针时不可以

 1 1 //header files...
 2  2 using namespace std;
 3  3 class A
 4  4 {
 5  5 private:
 6  6     int a;
 7  7 public:
 8  8     A(int a_):a(a_){}
 9  9     void operator(){cout<<a<<endl;}
10 10 };
11 11 int main(int argc,char** argv)
12 12 {
13 13     A a1(5);
14 14     A *pA=new A(7);
15 15     a1();//correct using operator() function
16 16     (*pA)();//pA() is not correct
17 17 }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM