[C++] 纯文本查看 复制代码
#include <iostream>
using namespace std;
class Point {
public:
Point( int = 0, int = 0 ); //默认构造函数
~Point(); //析构函数
protected:
int x, y; //可以被派生类访问
};
Point::Point( int a, int b )
{
x = a;
y = b;
cout << "Point constructor: "
<< '[' << x << ", " << y << ']' << endl;
}
Point::~Point()
{
cout << "Point destructor: "
<< '[' << x << "," << y << ']' << endl;
}
class Circle : public Point {
public:
Circle( double r = 0.0, int x = 0, int y = 0 );
~Circle();
private:
double radius;
};
Circle::Circle( double r, int a, int b ) : Point( a, b ) //调用基类构造函数
{
radius = r; //合法
cout << "Circle constructor: radius is " << radius
<< '[' << x << "," << y << ']' << endl;
}
Circle::~Circle()
{
cout << "Circle destructor: radius is " << radius
<< '[' << x << "," << y << ']' << endl;
}
int main()
{
Point p(11, 32);
cout << endl;
Circle circle1( 4.5, 72, 29 );
cout << endl;
Circle circle2(10, 5, 5);
cout << endl;
return 0;
}
[C++] 纯文本查看 复制代码
#include <iostream>
#include <typeinfo>
#include <cstdlib>
using namespace std;
class figure {
protected:
double x, y;
public:
figure(double i, double j)
{
x = i;
y = j;
}
virtual double area() = 0; //纯虚函数
};
class triangle : public figure {
public:
triangle(double i, double j) : figure(i, j) { };
double area()
{
return x * 0.5 * y;
}
};
class rectangle : public figure {
public:
rectangle(double i, double j) : figure(i, j) { }
double area()
{
return x * y;
}
};
class circle : public figure {
public:
circle(double i, double j = 0) : figure(i, j) { }
double area()
{
return 3.14 * x * x;
}
};
figure *factory ()
{
switch(rand() % 3) {
case 0:
return new circle(10.0);
case 1:
return new triangle(10.1, 5.3);
case 2:
return new rectangle(4.3, 5.7);
}
return 0;
}
int main()
{
figure *p; //指向基类的指针
int i;
int t = 0, r = 0, c = 0;
//生成并统计对象
for (i = 0; i < 10; i++) {
p = factory(); //生成一个对象
cout << "Object is " << typeid(*p).name();
cout << ". ";
//统计对象
if (typeid(*p) == typeid(triangle)) t++;
if (typeid(*p) == typeid(rectangle)) r++;
if (typeid(*p) == typeid(circle)) c++;
//输出对象的面积
cout << "Area is " << p->area() << endl;
}
cout << endl;
cout << "Objects generated:\n";
cout << "Triangles: " << t << endl;
cout << "Rectangles: " << r << endl;
cout << "Circles: " << c << endl;
return 0;
}