30 31
C++返回对象和引用的区别
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;
}
};
//拷贝构造发生的时机
//1.构造新对象 A a ; A b = a;
//2.传参或返回对象
//对于普通变量来说,传引用效果不明显
//对于类对象而言,传对象效率很高
//传引用等价于 扩大了原对象的作用域
//栈上的对象是可以返回的,但不能返回栈上的引用(除非返回对象本身)
void func(A a)
{
}
int main()
{
A x;
A y = x;
func(x);//发生一次拷贝构造 函数不是引用的话 引用的话 就没有拷贝构造了
return 0;
}
A func(A &a)
{
return a;
}
int main()//一次构造 一次拷贝构造
{
A x;
A t = func(x);
cout<<"&t "<<&t<<endl;
return 0;
}
int main()//两次构造 一次拷贝构造 一次operator= 然后立马析构拷贝构造的临时变量
{
A x;
A t;
t= func(x);
cout<<"&t "<<&t<<endl;
return 0;
}
A func()
{
A b;
return b;
}
int main()//两次拷贝 一次operator = 然后立马析构b的
{
A t;
t= func();
cout<<"&t "<<&t<<endl;
return 0;
}
加法 大于 小于 等于 [] at
class myString
{
public:
myString(const char *p = NULL);//默认参数只能在声明
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;//本质 xx.operator+(yy);
cout<<xx[2]<<endl;
}