1.重载=运算符
重载声明是指一个与之前已经在该作用域内声明过的函数或方法具有相同名称的声明,但是它们的参数列表和定义(实现)不相同。当调用一个重载函数或重载运算符时,编译器通过把您所使用的参数类型与定义中的参数类型进行比较,决定选用最合适的定义。
当我们进行类之间的定义和拷贝的时候,有的时候调用的是拷贝构造函数,有的时候调用的是重载的赋值运算符
(1)首先定义一个类,在类内进行赋值运算符的定义
class Time
{
public:
int Hour;
int Minute;
int Second;
public:
Time& operator=(const Time&);//重载赋值运算符,注意定义的方式
};
Time mytime4 = mytime3;//调用拷贝构造函数
Time mytime6;
mytime6 = mytime3;//赋值运算符,即没有调用拷贝构造函数,也没有调用默认构造函数,但是系统会调用一个拷贝赋值运算符(我们可以自己重载,或者系统自动生成,如果成员是一个类,系统还会调用该类的拷贝赋值运算符)
(2)实现
Time& Time::operator=(const Time& tmpobj)//重载赋值运算符
{
//mytime5传递给了const Time,mytime6就是this
Hour = tmpobj.Hour;
Minute = tmpobj.Minute;
Second = tmpobj.Second;
cout << "调用了Time& Time::operator=(const Time&)赋值运算符重载" << endl;
return *this;
}
2.重载()运算符
class linear
{
private:
double slope;
double y;
public:
linear(double sl_ = 3, double y_ = 2) :slope(sl_), y(y_) {}
double operator()(double x) { return y + slope*x; }//注意定义的方式
};
int main()
{
linear f2;
linear f1(2.5, 10);
double c = f2(20);
double d = f1(0.2);
cout << c << endl;
cout << d << endl;
return 0;
}