今天在調試一個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