class Str; 类名
//x坐标
int x;
//y 坐标
int y;
//无参构造
Str::Str()
{
x = 0;
y = 0;
}
//有参数的构造
Str::Str(int _x,int _y)
{
x = _x;
y = _y;
}
//get方法
int Str::getX()const
{
return x;
}
int Str::getY()const
{
return y;
}
//返回
int Str::print()
{
return getX();
}
注解:关于const:
/*
为什么需要const成员函数?
我们定义的类的成员函数中,常常有一些成员函数不改变类的数据成员,
也就是说,这些函数是"只读"函数,就像get方法,返回指定的值,而有一些函数要修改类数据成员的值。
把不改变数据成员的函数都加上const关键字进行标识,可提高程序的可读性,
还能提高程序的可靠性,已定义成const的成员函数,一旦企图修改数据成员的值,则编译器按错误处理。
*/
/*
如果const在最前面,则代表着返回值是不可改变的(在执行return语句之前可以改变),
如果在函数名的后面,则代表着在函数体中变量是不可修改的
*/
1. 输出运算符重载:
friend ostream& operator<<(ostream& out,const Str& s); (声明)
ostream& operator<<(ostream& out,const Str& s) (实现)
{
out<<"x的值:"<<s.getX()<<" y的值:"<<s.getY()<<endl;
}
//检测
cout<<"--------------输出运算符重载--------------"<<endl;
Str s0(4,4);
cout<<s0<<endl;
注解:1.关于定义为友元函数的问题:
如果是类的成员函数,就只要设置一个参数作为右侧运算量,而左侧运算量就是对象本身
而定义为友元的运算符重载要求运算符左操作数为运算符函数的第一个参数,
而流类库中的>>则要求第一个参数为ostream的引用,所以不能作为类成员,只能作为友元
2.我们可以看到有些函数前面要声明是属于类Str,为什么友元函数不加呢?
因为友元函数是指某些虽然不是类成员却能够访问类的所有成员的函数 ,所以不加Str:: 这种声明
2.赋值运算符重载:
// 返回一个str对象(参数最好定为const)
const Str& operator=(const Str& s); (声明)
const Str& Str::operator=(const Str& s) (实现)
{
if(this != &s)
{
x = s.x;
y = s.y;
return *this;
}
}
//检测
Str s1(4,4);
Str s2(2,3);
cout<<"--------------赋值运算符重载--------------"<<endl;
cout<<s1<<endl;
cout<<s2<<endl;
s1 = s2;
cout<<s1<<endl;
cout<<s2<<endl;
3.比较运算符重载:
friend bool operator>(const Str& s1,const Str& s2); (声明)
bool operator>(const Str& s1,const Str& s2) (实现)
{
return (s1.getX()>s2.getX() && s1.getY()>s2.getY());
}
//检测
Str s1(4,4);
Str s2(2,3);
cout<<"--------------比较运算符------------"<<endl;
int i = s2>s1;
cout<<i<<endl;
4. == 运算符重载
friend bool operator==(const Str& s1,const Str& s2); (声明)
bool operator==(const Str& s1,const Str& s2) (实现)
{
return (s1.getX()==s2.getX() && s1.getY()==s2.getY());
}
//检测
Str s1(4,4);
Str s2(2,3);
cout<<"--------------判断运算符------------"<<endl;
int j = (s1==s2);
cout<<j<<endl;
5. += 运算符重载:
/*
第一个参数:不能定义为const,因为它是做左值,是可以改变的
第二个参数:最好定义为const,作为右值的存在
*/
friend const Str& operator+=(Str& s1,const Str& s2); (声明)
const Str& operator+=(Str& s1,const Str& s2) (实现)
{
s1.x += s2.x;
s1.y += s2.y;
return s1;
}
//检测
Str s1(4,4);
Str s2(2,3);
cout<<"------------- += -----------------"<<endl;
s1 += s2;
cout<<s1<<endl;