重新复习一遍C++的
constructor, construct with arguments, copy constructor, copy assignment
下面重点要强调的是有关copy constructor,constructor ,和 copy assignment。
如果拷贝参数是对象的话,注意要使用常引用即 const &。 如果返回值是对象的话,返回的也是该对象的引用。
#include "iostream"
#include "string"
class CTime{
std::string *ptr;
public:
//default constructor
CTime(){}
//constructor with one parameter
CTime(const std::string &str):ptr(new std::string(str)){}
//Copy constructor
CTime(const CTime &x):ptr(new std::string(x.getContent())){}
//copy assignment
CTime& operator =(const CTime& x){
delete ptr;
ptr = new std::string(x.getContent());
return *this;
}
//destructor
~CTime(){
delete ptr;
}
//get content
const std::string& getContent() const{
return *ptr;
}
};
int main(){
CTime Timea("this is 11 o\'clolck ");
CTime Timeb("24");
CTime Timec(Timea);
Timeb = Timea;
std::cout << Timea.getContent() << std::endl;
std::cout << Timeb.getContent() << std::endl;
std::cout << Timec.getContent() << std::endl;
return 0;
}