题目:1327 平面上的点和线——Point类、Line类 (I)
1.正常解法:组合类
#include<iostream>
using namespace std;
class Point {
private :
double x,y;
public :
Point(){x = 0;y = 0;}
Point( double x1, double y1){x = x1; y = y1;}
void show(){cout<< "Point : (" <<x<< ", " <<y<< ")" <<endl;}
Point(Point &p){x = p.x;y = p.y; }
double getx(){return x;}
double gety(){return y;}
};
class Line {
private :
Point p,q;
public :
Line( double a, double b, double c, double d):p(a,b),q(c,d){}
void show(){ cout<< "Line : (" <<p.getx()<< ", " <<p.gety()<< ") to (" <<q.getx()<< ", " <<q.gety()<< ")" <<endl;}
Line(Point a,Point b):p(a),q(b){}
};
int main()
{
char c;
int num, i;
double x1, x2, y1, y2;
Point p(1, -2), q(2, -1), t;
t.show();
std::cin>>num;
for (i = 1; i <= num; i++)
{
std::cin>>x1>>c>>y1>>x2>>c>>y2;
Line line(x1, y1, x2, y2);
line.show();
}
Line l1(p, q), l2(p, t), l3(q, t), l4(t, q);
l1.show();
l2.show();
l3.show();
l4.show();
}
2.友元类:(参见c++小小包)(意义类似于将私有变共有,即使友元类有访问权限)
#include <iostream>
using namespace std;
class Point {
friend class Line;
private:
double x,y;
public:
Point():x(0),y(0) {}
Point(double x1, double y1) : x(x1), y(y1) {}
void show() {cout << "Point : (" << x << ", " << y << ")\n";}
};
class Line {
friend class Point;
private:
Point p, q;
public:
Line(Point p1, Point q1):p(p1), q(q1){}
Line(double x1, double y1, double x2, double y2): p(x1, y1), q(x2, y2){}
void show() {cout << "Line : (" << p.x << ", " << p.y << ") to (" << q.x << ", " << q.y << ")\n";}
};
int main()
{
char c;
int num, i;
double x1, x2, y1, y2;
Point p(1, -2), q(2, -1), t;
t.show();
std::cin>>num;
for(i = 1; i <= num; i++)
{
std::cin>>x1>>c>>y1>>x2>>c>>y2;
Line line(x1, y1, x2, y2);
line.show();
}
Line l1(p, q), l2(p, t), l3(q, t), l4(t, q);
l1.show();
l2.show();
l3.show();
l4.show();
}
3.投机取巧法:(将所有私有成员变成共有)
#include <iostream>
#include <algorithm>
#include <string>
#include <cstring>
#include <cstdlib>
#include <cmath>
using namespace std;
class Point {
public:
double x, y;
Point(double a=0, double b=0):x(a), y(b) {}
Point(Point& c) {
x = c.x;
y = c.y;
}
void show() {
cout << "Point : (" << x << ", " << y << ")" << endl;
}
};
class Line {
public:
Point a, b;
Line(double aa, double bb, double c, double d):a(aa, bb), b(c, d) {}
void show () {
cout << "Line : (" << a.x << ", " << a.y << ") to (" << b.x << ", " << b.y << ")" << endl;
}
Line(Point c, Point d):a(c), b(d) {}
};
int main()
{
char c;
int num, i;
double x1, x2, y1, y2;
Point p(1, -2), q(2, -1), t;
t.show();
std::cin>>num;
for(i = 1; i <= num; i++)
{
std::cin>>x1>>c>>y1>>x2>>c>>y2;
Line line(x1, y1, x2, y2);
line.show();
}
Line l1(p, q), l2(p, t), l3(q, t), l4(t, q);
l1.show();
l2.show();
l3.show();
l4.show();
}