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 }

 

原文链接: https://www.cnblogs.com/blog-vincent-0x1F7/p/9668512.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

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

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/281444

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月15日 上午5:40
下一篇 2023年2月15日 上午5:42

相关推荐