// c_datastructure.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
#include<string>
using namespace std;
class Point {
public:
Point(float x=0, float y=0);
void setXY(float, float);
float getX() const { return x; }
float getY() const { return y; }
friend ostream& operator << (ostream &, const Point &);
protected:
float x;
float y;
};
class Circle :public Point {
public:
Circle(float x, float y, float r) :Point(x, y), radius(r) {}
void setR(float r) { radius = r; }
float getR() const { return radius; }
float area() const { return (3.1415*radius*radius); }
friend ostream & operator << (ostream &, const Circle &);
private:
float radius;
};
class Cylinder :public Circle {
public:
Cylinder(float x, float y, float r, float h):Circle(x, y, r), height(h) {}
void setH(float h) { height = h; }
float getH() const { return height; }
float area() const;
float volume() const;
friend ostream& operator << (ostream &, const Cylinder &);
private:
float height;
};
Point::Point(float a, float b) :x(a), y(b) {}
void Point::setXY(float a, float b) {
x = a;
y = b;
}
ostream & operator << (ostream &output, const Point &p) {
output << "[" << p.x << ", " << p.y << "]" << endl;
return output;
}
ostream & operator << (ostream &output, const Circle &c) {
output << "center point: x= " << c.x << ", " << c.y <<
" radius= " << c.radius << " area= " << c.area() << endl;
return output;
}
float Cylinder::area() const {
return 2 * Circle::area() + 2 * 3.1415*Circle::getR()*height;
}
float Cylinder::volume() const {
return Circle::area()*height;
}
ostream& operator << (ostream &output, const Cylinder &c) {
output << "center point: " << "[" << c.x << ", " << c.y <<
"]; r= " << c.getR() << " area= " << c.area() << " volun= " << c.volume() << endl;
return output;
}
int main()
{
cout << "************" << endl;
Point p(1.9, 2.7);
cout << "x= " << p.getX() << " " << "y= " << p.getY() << endl;
p.setXY(22.22, 4.1);
cout << p << endl;
Circle c(1, 2, 3);
c.setR(5);
cout << " radius= " << c.getR() << endl;
cout << c << endl;
Circle *ctr = &c;
cout << *ctr << endl;
Cylinder cc(5, 5, 7.5, 7);
cc.setH(15);
cout << cc << endl;
Point &cctr = cc;
Circle &ccctr = cc;
cout << cctr << endl;
cout << ccctr << endl;
// system("pause");
/*
int A[] = { 1, -2, 3, 10, -4, 7, 2 };
int maxSum = maxSubArray_baoli(A, 7);
cout << maxSum << endl;
cout << maxSubArray_fenzhi(A, 0, 7) << endl;
cout << maxSubArray_dongtaiguihua(A, 7) << endl;
*/
return 0;
}
int gcd(int x, int y) {
return y == 0 ? x : gcd(y, x%y);
}
这段代码中仅仅是在circle和cylinder类中分别定义are()函数,属于一种函数重载的运算,系统编译时候通过具体对象去调用该函数从而实现不同的功能。这个仅仅算是静态的关联。
代码运行结果: