一、成员函数
1.成员函数的声明必须在类内,但是定义可以在类外,类外的成员函数声明处要加 类名::
string date::cmb(string s1, string s2)
{
return s1 + s2;
}
struct date
{
int x, y;
int xx()
{
return x;
}
string cmb(string s1, string s2);
};
2.在上述类中,xx函数返回x的值是通过名为this的额外的隐式参数来实现的,将返回调用函数的对象下的x成员,具体过程如下:编译器把item的地址传给xx的隐式形参this,也就是调用xx成员时传入了item的地址,在成员函数(xx)内部可以直接调用该函数的对象(item)的成员(x)
date item;
item.xx();
3.由于this的目的是总是指着对应对象,所以this是一个常量指针,成员函数还可以写成如下形式:
int xx() const
{
return this->x;
}
4.上面定义的xx中const作用是修改隐式this指针的类型。默认情况下,this的类型是指向类类型非常量版本的常量指针,因此不能把this绑定到一个常量对象上,即不能在常量对象上调用普通的成员函数。在c++中允许把const关键字放在成员函数的参数列表之后来表示this是一个常量指针
5.像这样使用const的成员函数被称作常量成员函数,常量对象以及常量的引用、指针都只能调用常量成员函数
6.在类外定义常量成员函数时:要在参数列表后明确指定const属性,类外部定义的成员的名字必须包含他所属的类名
int date::xx() const
{
return this->x;
}
struct date
{
int x, y;
int xx() const;
};
7.可以定义返回this对象的函数,
date& date::cmb(const date& temp)
{
s += temp.s; //其中s,x分别代表this.s,this.x
x += temp.x;
return *this; //返回对象的引用
}
struct date
{
int x;
string s;
date& cmb(const date& temp);
};
void solve()
{
date item1, item2;
item1.cmb(item2);
}
二、定义类相关的非成员函数
1.定义read、print,其中read和print分别接受一个各自IO类型的引用作为参数,这是因为,IO类属于不能拷贝的类型,因此我们只能通过引用来传递他们。因为读取和写入的操作会改变流的内容,所以这两个函数接受的都是普通引用,而非常量引用
istream& read(istream& in, date& item)
{
in >> item.x >> item.s;
return in;
}
ostream& print(ostream& out, date& item)
{
out << item.x << ' ' << item.s << ' ';
return out;
}
struct date
{
int x;
string s;
};