Overloading and Function Selection

C++ For C Programmers 4.5 Overloading and Function Selection

1 class point{
2 public:
3 point(double u):x(u),y(0.0){}
4 ...
5 private double x,y;
6 };

point(double u):x(u),y(0.0) {}是一种隐式类型转换,如果我把u=5赋值给一个point,则会把u=5转换成 point u = (5.0, 0.0).C++会自动帮你转换,但是你也可以尝试在point(double u):x(u), y(0.0){}前加explicit然后使用static_cast<point>(u)进行手动转换。

point ::operator double()
{ return sqrt(x*x + y*y);}

一种把point转换成double的方式,改变了C++double的规则,从此使用d = s; 就会运行,不然的话会报错

class point{
...
private:
double x,y; 
};

ostream& operator<<(ostream& out, const point& p)
{out << "(" << x << y << ")"; return out;}

运行失败,因为x,y是private,不能直接传递给其他函数。

class point{
friend ostream& operator<<(ostream& ..);
private:
double x,y;
};

这个时候就可以使用friend功能,让其变为friend fuction。

class point{
public:
point operator+(point p)
{return point(x+p.x, y+p.y);}
...
private double x,y;
};

首先使用了member fuction,这种方式的局限性在于点a+点b的值会自动赋给点a。

猜你喜欢

转载自www.cnblogs.com/freeblacktea/p/10222604.html
今日推荐