求一个讲述友元函数的c++程序~!
一个c++程序(主要讲友元函数的)
- 提问者网友:一抹荒凉废墟
- 2021-07-31 15:14
- 五星知识达人网友:神的生死簿
- 2021-07-31 16:31
#include<iostream>
#include<cmath>
using namespace std;
class Point
{
public:
Point(int xx=0,int yy=0){X=xx;Y=yy;}
int GetX(){return X;}
int GetY(){return Y;}
friend float fDist(Point &a,Point &b);//友元函数
private:
int X,Y;
};
float fDist(Point &p1,Point &p2)//友元函数定义
{
double x=double(p1.X-p2.X);
double y=double(p1.Y-p2.Y);
return float(sqrt(x*x+y*y));
}
void main()
{
int x,y;
cout<<"Please input the first point(X Y):";
cin>>x>>y;
Point mp1(x,y);
cout<<"Please input the second point(X Y):";
cin>>x>>y;
Point mp2(x,y);
cout<<"The length of the Point1 between Point2 is:"<<fDist(mp1,mp2)<<endl;//调用友元函数
}
结果
- 1楼网友:想偏头吻你
- 2021-07-31 17:32
#include "stdafx.h" //#ifndef _obj_ //#define _obj_ #include <iostream> using namespace std; class obj { private: int x,y; friend ostream &operator<<(ostream&,const obj&); friend istream &operator>>(istream&,obj&); }; //#endif //_obj_
ostream &operator<<(ostream& os,const obj& rhs) { os<<rhs.x<<rhs.y; return os; // enables cout << a << b << c; }
istream &operator>>(istream &is, obj &o) { is >> o.x; is >> o.y; return is; // enables cin >> a >> b >> c; }
int main(){ obj a; cin >> a; cout << a << endl;
system("pause"); }
- 2楼网友:过活
- 2021-07-31 16:51
class Clock { public: Clock(int NewH=0,int NewM=0,int NewS=0); void ShowTime(); // void operator ++(); friend void operator ++(Clock c1); // void operator ++(int); friend void operator ++(Clock c1,int); private: int Hour,Minute,Second; };
Clock::Clock(int NewH,int NewM,int NewS) { if(NewH>=0&&NewH <24&&NewM>=0&&NewM <60&&NewS>=0&&NewS <60) { Hour=NewH; Minute=NewM; Second=NewS; } else { cout <<"Time error!" <<endl; } }
void Clock::ShowTime() { cout <<Hour <<":" <<Minute <<":" <<Second <<endl; }
//void Clock::operator ++() void operator ++(Clock c1) { // Second++; c1.Second++; // if(Second>=60) if(c1.Second>=60) { // Second=Second-60; c1.Second=c1.Second-60; // Minute++; c1.Minute++; // if(Minute>=60) if(c1.Minute>=60) { // Minute=Minute-60; c1.Minute=c1.Minute-60; // Hour++; c1.Hour++; // Hour=Hour%24; c1.Hour=c1.Hour%24; } } cout <<"++myClock"; }
//void Clock::operator ++(int) void operator ++(Clock c2,int) { // Second++; c2.Second++; // if(Second>=60) if(c2.Second>=60) { // Second=Second-60; c2.Second=c2.Second-60; // Minute++; c2.Minute++; // if(Minute>=60) if(c2.Minute>=60) { // Minute=Minute-60; c2.Minute=c2.Minute-60; // Hour++; c2.Hour++; // Hour=Hour%24; c2.Hour=c2.Hour%24; } } cout <<"myClock++"; }
int main() { Clock myClock(23,59,59); cout <<"First time output:"; myClock.ShowTime(); myClock++; myClock.ShowTime(); ++myClock; myClock.ShowTime(); }