// 對象做函數參數和返回值.cpp : 定義控制台應用程序的入口點。
//exit(0)表示正常退出程序,exit(0)表示異常退出
//在調用input時,編譯器用對象A去創建了形參對象temp,調用了復制構造函數,對象A中的數據復制給了對象temp
// 在input函數中,執行temp.set(s),為對象temp中數據成員str申請了動態儲存空間,並設置了輸入的字符串
//並沒有改變實參A中的數據成員str的儲存空間,故在執行語句A.show()后輸出的字符串並沒有改變。在函數調用結束后
//將對象temp做為函數返回值來創建對象B,所以對象B的數據成員str的值是調用input函數時輸入的字符串
#include<iostream>
#include<cstring>
using namespace std;
class Cstream
{
public:
Cstream(char *s);
Cstream(const Cstream& temp);//copy constructor function
~Cstream();
void show();
void set(char *s);
private:
char *str;
};
Cstream::Cstream(char * s)
{
cout << "constructor" << endl;
str = new char[strlen(s) + 1];
if (!str)
{
cerr << "Allocation Error" << endl;
exit(1);//error 退出程序
}
strcpy(str, s);
}
Cstream::Cstream(const Cstream & temp)
{
cout << "copy constructor" << endl;
str = new char[strlen(temp.str) + 1];
if (!str)
{
cerr << "error in apply new space" << endl;
exit(1);
}
strcpy(str,temp.str);
}
Cstream::~Cstream()
{
cout << "destructor" << endl;
if (str != NULL)
delete[] str;//釋放str指向的儲存空間
}
void Cstream::show()
{
cout << str << endl;
}
void Cstream::set(char * s)
{
delete[] str;
str = new char[strlen(s) + 1];
if (!str)
{
cerr << "Allocation Error" << endl;
exit(1);
}
strcpy(str, s);
}
Cstream input(Cstream temp)//對象作為參數和返回值的普通函數
{
char s[20];
cout << "please input the string:";
cin >> s;//輸入新字符串
temp.set(s);//賦值新字符串
return temp;//返回對象
}
int main()
{
Cstream A("Hello");
A.show();
Cstream B = input(A);//用input的函數值初始化對象B
A.show();
B.show();
return 0;
}