#include <iostream>
#include <string>
class CTest {
private:
string m_message; /* 設定字串變數 */
public:
string& ResultByRef(int a,int b) /* 設定回傳值為字串,參數為整數a、b */
{
this->m_message=""; /* 初始化m_message為空字元,this表示為此CTest class的意思 */
char szBuf[100]; /* 設定字元陣列 */
sprintf(szBuf,"a+b=%d",a+b); /* 將字串a+b=%d(=a+b=10) 寫入到szBuf */
this->m_message=szBuf;
return this->m_message; /* 回傳m_message字串 */
}
string ResultByValue(int a,int b) /* 設定回傳值為字串,參數為整數a、b */
{
string strTmp; /* 設定字串變數 */
char szBuf[100]; /* 設定字元陣列 */
sprintf(szBuf,"a+b=%d",a+b); /* 將字串a+b=%d(=a+b=10) 寫入到szBuf */
strTmp=szBuf; /* 將szBuf指定給strTmp */
return strTmp; /* 回傳strTmp字串 */
}
};
int main()
{
CTest test;
cout << test.ResultByRef(10,10) << endl; /* 列印出函數 test.ResultByRef(10,10)結果 */
cout << test.ResultByValue(10,10) << endl; /* 列印出函數 test.ResultByValue(10,10)結果 */
system("PAUSE"); /* 調用系統指令讓顯示結果的視窗停止,以避免跑完結果視窗直接結束 */
return 0;
}
實驗結果:
參考資料:
http://phorum.study-area.org/index.php?topic=50210.0