友元函数的例子:
#include<iostream>
#include<stdio.h>
using namespace std;
class point
{
friend void show(point & );
public:
point()
{}
point(int x,int y):x(x),y(y)
{}
point (point &sd)
{
x = sd.x;
y = sd.y;
}
point &operator = (point &sd)
{
if(this != &sd)
{
x= sd.x;
y = sd.y;
}
return *this;
}
~point()
{}
private:
int x;
int y;
};
void show(point &sd) //将类的共有方法声明为友元方法,即就打破封装性,他就和
//普通方法一样可以直接访问私有数据
{
cout<<"x = "<< sd.x<<endl;
}
int main()
{
point a(1,3);
//a.show(); //当要访问一个类的私有数据时,必须要通过共有方法进行访问
show(a); //当声明为友缘,则就像其闺蜜,1.可以访问私有数据,2.不需要对象激活
return 0;
}
运行结果:
x = 1
Press any key to continue
下面实现常见的运算符重载:
先解决一下 i++ 与++i 的区别:
先看前++ ++i 注意这里 i 是一个对象
#include<iostream>
#include<stdio.h>
using namespace std;
class point
{
friend void show(point & );
public:
point& operator ++()
{
x = x + 1;
y = y + 1;
return *this;
}
public:
point()
{}
point(int x,int y):x(x),y(y)
{}
point (point &sd)
{
x = sd.x;
y = sd.y;
}
point &operator = (point &sd)
{
if(this != &sd)
{
x= sd.x;
y = sd.y;
}
return *this;
}
~point()
{}
private:
int x;
int y;
};
void show(point &sd)
{
cout<<"x = "<< sd.x<<endl;
cout <<"y = "<<sd.y<<endl;
}
int main()
{
point a(1,3);
show(a);
a++;
show(a);
a.operator ++();
show(a);
return 0;
}
运行结果
x = 1
y = 3
x = 2
y = 4
x = 3
y = 5
Press any key to continue
所以调动运算符重载函数 两种方式: 1. a++; 2. a.operator ++() //相当调用对象调用公有方法
再看I++
#include<iostream>
#include<stdio.h>
using namespace std;
class point
{
friend void show(point & );
public:
point& operator ++(int )
{
point temp (this ->x,this -> y);
x = x + 1;
y = y + 1;
return temp;
}
public:
point()
{}
point(int x,int y):x(x),y(y)
{}
point (point &sd)
{
x = sd.x;
y = sd.y;
}
point &operator = (point &sd)
{
if(this != &sd)
{
x= sd.x;
y = sd.y;
}
return *this;
}
~point()
{}
private:
int x;
int y;
};
void show(point &sd)
{
cout<<"x = "<< sd.x<<endl;
cout <<"y = "<<sd.y<<endl;
}
int main()
{
point a(1,3);
show(a);
a++;
show(a);
a.operator ++(1);
show(a);
return 0;
}
运行结果:
x = 1
y = 3
x = 2
y = 4
x = 3
y = 5
Press any key to continue
可看出,运算符重载是对重载函数的使用,靠得是参数列表进行调用,例如 I++ 调用 operator ++(int ) ++I 调用operator ++()
好了,下节再聊其他的。吃饭ing