c++ 关于前向引用的错误使用问题

今天在调试一个demo 程序:

 #include <stdlib.h>
#include <stdio.h>
 #include <math.h>
 class Result;
 class MathCallBack
 {
     int ops1,ops2;
     int result;
 public:
     void Add(int a,int b,Result *caller,CallbackPtr callback)
     {
         ops1 = abs(a);  
         ops2 = abs(b);

         result = ops1+ops2;

         (caller->*callback)(result);
     }

    void Add(int a,int b,Result &callerClass)
     {
         ops1 = abs(a);  
         ops2 = abs(b);

         result = ops1+ops2;
        printf("caller pointer =%p\n",&callerClass);
        callerClass.showResult(result);
     }
 };
 class Result
 {
 public:
     void showResult(int res)
     {
         printf("result = %d\n",res);
     }
 };
int main(int argc, char* argv[])
 {
     Result reShow;
     Result &reShow1=reShow;
     MathCallBack math;
     printf("caller pointer =%p\n",&reShow1);
     math.Add(1,3,&reShow,&Result::showResult);
     math.Add(2,2,reShow);
     return 0;
 }
通过下面命令编译:

g++ -o test1 test1.cpp

报下面错误:

test1.cpp: In member function ‘void MathCallBack::Add(int, int, Result&)’:
test1.cpp:32:20: error: invalid use of incomplete type ‘class Result’
         callerClass.showResult(result);
                    ^
test1.cpp:8:8: error: forward declaration of ‘class Result’
  class Result;
        ^
通过分析该问题是由于在类未定义时调用该类的成员函数,无法找到该成员函数。

下面是关于前向引用说明:

可以声明一个类而不定义它
   class Screen;//declaration of the Screen class
   这个声明,有时候被称为前向声明(forward declaration),在程序中引入了类类型的Screen.在声明之后,定义之前,类Screen是一个不完全类型(incompete type),即已知Screen是一个类型,但不知道包含哪些成员.
   不完全类型只能以有限方式使用,不能定义该类型的对象,不完全类型只能用于定义指向该类型的指针及引用,或者用于声明(而不是定义)使用该类型作为形参类型或返回类型的函数.

引自:http://blog.chinaunix.net/uid-209416-id-2888131.html

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值