简单的问题求解答
本帖最后由 yuanhaosh 于 2013-01-28 14:20:07 编辑 问题在1,2还望大家不吝惜赐教
#include <iostream.h>
class Base
{
public:
void f(int x){ cout << "Base::f(int) " << x << endl; }
void f(float x){ cout << "Base::f(float) " << x << endl; }
virtual void g(void){ cout << "Base::g(void)" << endl;}
};
class Derived : public Base
{
public:
virtual void g(void){ cout << "Derived::g(void)" << endl;}
};
void main(void)
{
Derived d; //直接用d.g()也行啊,为什么要这样 ?1111111111111111111
Base *pb = &d; //这样做的好处是什么?22222222222222222222222
pb->f(42); // Base::f(int) 42
pb->f(3.14f); // Base::f(float) 3.14
pb->g(); // Derived::g(void)
d.g();
d.f(324);
d.f(324.00f);
}
# include <iostream>
# include <vector>
using namespace std;
class Shape {
public:
virtual double area() = 0;
virtual ~Shape() {}
};
class Square : public Shape {
double side;
public:
Square(double side) { this->side = side; }
double area() {
return side * side;
}
};
class Rectangle : public Shape {
double a, b;
public:
Rectangle(double a, double b) { this->a = a; this->b = b; }
double area() {
return a * b;
}
};
class Circle : public Shape {
double r;
public:
Circle(double r) { this->r = r; }
double area() {
return 3.14 * r * r;
}
};
int main()
{
vector<Shape *> v;
v.push_back(new Square(4));
v.push_back(new Rectangle(3, 4));
v.push_back(new Circle(4));
vector<Shape *>::iterator it = v.begin();
for (; it != v.end(); it++)
cout << (*it)->area() << endl;
it = v.begin();
for (; it != v.end(); it++)
delete (*it);
return 0;
}