The object does the function parameter and the return value. CPP: The entry point that defines the console application.
Exit (0) indicates normal exit program, exit (0) indicates exception exit
When input is called, the compiler creates the parameter object temp with Object A, calls the copy constructor, and the data in object A is copied to the object temp
In the input function, execute temp.set (s), request dynamic storage for data member str in object temp, and set the input string
Does not change the storage space of the data member Str in argument A, so the string that is output after executing the statement a.show () does not change. After the function call ends
Object TEMP is created as a function return value to create object B, so the value of object B's data member Str is the string entered when the input function is called
#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 Exit Program
}
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;//releases the storage space that Str points to
}
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)//object as a normal function for parameters and return values
{
Char s[20];
cout << "Please input the string:";
CIN >> s;//Enter new string
Temp.set (s);//Assign new string
Return temp;//returns the object
}
int main ()
{
Cstream A ("Hello");
A.show ();
Cstream B = input (A);//Initialize object B with the function value of input
A.show ();
B.show ();
return 0;
}
When an object does a function parameter and a function return value, call the copy constructor, constructor, and destructor