(1)链式赋值:
举个简单例子(就拿赋值运算符函数):
#include <iostream>
using namespace std;
class complex
{
public:
complex() :real(0), ima(0){} //无参构造函数
complex(double a, double b) :real(a), ima(b) {} //带参构造函数{}
~complex() {} //析构函数
complex(const complex& right); //声明拷贝构造函数
complex& operator=(const complex& right); //声明赋值运算符函数
void display(); //输出函数
private:
double real, ima;
};
complex::complex(const complex& right) //拷贝构造函数
{
real = right.real;
ima = right.ima;
}
complex& complex::operator=(const complex& right) //赋值运算符函数
{
if (this == &right)
return *this;
real = right.real;
ima = right.ima;
return *this;
}
void complex::display() //输出函数
{
if (ima == 0)
cout << "(" << real << "," << ima << ")";
else
cout << "(" << real << "," << ima << "i" << ")";
cout << endl;
}
int main()
{
complex c1(3,4), c2(5,-10), c3(1,-20);
cout << "c1 = ";
c1.display();
cout << "c2 = ";
c2.display();
cout << "c3 = ";
c3.display();
cout << endl;
//接下来进行链式赋值,将c3赋值给c2和c1
c1 = c2 = c3;
//输出c1,c2,c3的值
cout << "c1 = ";
c1.display();
cout << "c2 = ";
c2.display();
cout << "c3 = ";
c3.display();
}
这里的c1 = c2 = c3;是隐式调用,显示调用可以更好的理解: c1.operator( c2.operatpr( c3 ) ) 。在这个式子里可以清楚的看见,c2.operatpr( c3 )这个函数的返回值作为 c1.operator( 参数 )这个函数的参数
(2)临时对象:
在运算符重载函数等内容时,我们会接触到这个内容,比如
//#include <iostream>
using namespace std;
class Complex //复数类
{
public:
Complex() : real(0), imag(0) {} //缺省构造函数
Complex(double real, double imag); //带参数的构造函数
Complex(const Complex &right); //拷贝构造函数
~Complex() {} //析构函数
Complex operator++(int); //后置运算符 c++
Complex operator--(int); //后置运算符 c--
private:
double real; // real number
double imag; // imaginary number
};
Complex::Complex(double real, double imag)
{
//cout << "Complex General Construnctor!" << endl;
this->real = real;
this->imag = imag;
}
//拷贝构造函数
Complex::Complex(const Complex &right)
{
//cout << "Complex copy constructor!" << endl;
real = right.real;
imag = right.imag;
}
Complex Complex::operator++(int)
{
Complex temp = *this; //调用拷贝构造函数
real++;
imag++;
return temp; //局部对象不能返回引用(reference)
}
Complex Complex::operator--(int)
{
Complex temp = *this; //调用拷贝构造函数
real++;
imag++;
return temp;
}
比如这里的后置自增和后置自减函数,当返回类型为类的对象的时候,系统会有一个隐式操作,产生一个临时对象。
#include <iostream>
using namespace std;
class Myclass
{
public:
Myclass operator=(const Myclass& other);
};
Myclass Myclass::operator=(const Myclass& other)
{
//...赋值操作...
return *this; //返回对象,触发拷贝函数
}
当调用a = b时:
1. 执行赋值操作:将 b 的值赋给 a(此时 a 的内容已正确更新)。
2. 生成临时对象:由于函数返回类型是 MyClass(而非引用),编译器会隐式地执行以下操作:
MyClass temp(*this); // 调用拷贝构造函数,生成临时对象
3. 返回临时对象:这个临时对象会被传递给链式赋值的下一个操作(如 `a = b = c` 中的后续 `a = temp`)。
4. **销毁临时对象**:临时对象在表达式结束后立即析构。

598

被折叠的 条评论
为什么被折叠?



