30 31
C++返回對(duì)象和引用的區(qū)別
class A
{
punlic:
A()
{
cout<<this<<" constructor"<<endl;
}
~A()
{
cout<<this<<" destructor"<<endl;
}
A(const A & another)
{
cout<<this<<" cpy constructor from"<<&another<<endl;
}
A& operator = (const A & another)
{
cout<<this<<" operator ="<<&another<<endl;
}
};
//拷貝構(gòu)造發(fā)生的時(shí)機(jī)
//1.構(gòu)造新對(duì)象 A a ; A b = a;
//2.傳參或返回對(duì)象
//對(duì)于普通變量來說区转,傳引用效果不明顯
//對(duì)于類對(duì)象而言,傳對(duì)象效率很高
//傳引用等價(jià)于 擴(kuò)大了原對(duì)象的作用域
//棧上的對(duì)象是可以返回的胯盯,但不能返回棧上的引用(除非返回對(duì)象本身)
void func(A a)
{
}
int main()
{
A x;
A y = x;
func(x);//發(fā)生一次拷貝構(gòu)造 函數(shù)不是引用的話 引用的話 就沒有拷貝構(gòu)造了
return 0;
}
A func(A &a)
{
return a;
}
int main()//一次構(gòu)造 一次拷貝構(gòu)造
{
A x;
A t = func(x);
cout<<"&t "<<&t<<endl;
return 0;
}
int main()//兩次構(gòu)造 一次拷貝構(gòu)造 一次operator= 然后立馬析構(gòu)拷貝構(gòu)造的臨時(shí)變量
{
A x;
A t;
t= func(x);
cout<<"&t "<<&t<<endl;
return 0;
}
A func()
{
A b;
return b;
}
int main()//兩次拷貝 一次operator = 然后立馬析構(gòu)b的
{
A t;
t= func();
cout<<"&t "<<&t<<endl;
return 0;
}
加法 大于 小于 等于 [] at
class myString
{
public:
myString(const char *p = NULL);//默認(rèn)參數(shù)只能在聲明
myString(const myString & another);
myString& operator=(const myString & another);
~myString()车柠;
myString operator+(const myString &another );
bool operator>(const myString &another );
bool operator<(const myString &another );
bool operator==(const myString &another );
char& operator[](int idx);
char at(int idx);
char *c_str();
private:
char *_str;
}
myString myString::operator+(const myString &another)
{
myString tmp;//char *=""; *this char * = "abcd",another char*="efg"
delete []tmp._str;
int len = strlen(this->_str);
len += strlen(another._str);
tmp._str = new char[len+1];
memset(tmp._str,0,len+1);
strcat(tmp._str,this->_str);
strcat(tmp._str,another._str);
return tmp;
}
bool myString::operator>(const myString &another )
{
if(strcmp(this->_str,another._str)>0)
return true;
else
return false;
}
bool myString::operator<(const myString &another )
{
if(strcmp(this->_str,another._str)<0)
return true;
else
return false;
}
bool myString::operator==(const myString &another )
{
if(strcmp(this->_str,another._str)==0)
return true;
else
return false;
}
char& myString::operator[](int idx)//xx[2] xx.operator[](int idx)
{
return this->_str[idx];
}
char myString::at(int idx)
{
return this->_str[idx];
}
int main()
{
string x= "abc",y="efg";
string z= x+y;
cout<<z.c_str()<<endl;
myString xx="abcd",yy ="efg";
myString zz= xx +yy;//本質(zhì) xx.operator+(yy);
cout<<xx[2]<<endl;
}