虚函数
#include <iostream>
using namespace std;
const double PI = 3.1415926;
class cpoint
{
public:
cpoint(double a, double b)
{
x = a;
y = b;
}
double area()
{
return 0;
}
private:
double x, y;
};
class ccircle :public cpoint
{
public:
ccircle(double a, double b, double c) :cpoint(a, b)
{
r = c;
}
double area()
{
return PI * r * r;
}
private:
double r;
};
class cractangle :public cpoint
{
public:
cractangle(double a, double b, double c, double d) :cpoint(a, b)
{
w = c;
h = d;
}
private:
double w, h;
};
void funcarea(cpoint& p)
{
cout << "area=" << p.area() << endl;
}
int main()
{
ccircle cobj(5.5, 6.6, 10);
funcarea(cobj);
cractangle cobjc(3, 4, 5, 6);
funcarea(cobjc);
return 0;
}
#include <iostream>
#include <string>
using namespace std;
class canimal
{
public:
virtual void callfunc();
private:
string name;
};
class ccattle :public canimal
{
public:
virtual void callfunc();
private:
int age;
};
class cdog :public canimal
{
public:
virtual void callfunc();
private:
int age;
};
void callfunc(canimal* p)
{
p->callfunc();
}
void canimal::callfunc()
{
cout << "动物此类不知道怎么叫...." << endl;
}
void ccattle::callfunc()
{
cout << "哞哞叫" << endl;
}
void cdog::callfunc()
{
cout << "汪汪叫" << endl;
}
int main()
{
ccattle cobj;
callfunc(&cobj);
cdog dobj;
callfunc(&dobj);
canimal aobj;
callfunc(&aobj);
return 0;
}
抽象类
#include <iostream>
#include <string>
using namespace std;
class canimal
{
public:
virtual void callfunc()=0;
private:
string name;
};
class ccattle :public canimal
{
public:
virtual void callfunc();
private:
int age;
};
class cdog :public canimal
{
public:
virtual void callfunc();
private:
int age;
};
void callfunc(canimal* p)
{
p->callfunc();
}
void ccattle::callfunc()
{
cout << "哞哞叫" << endl;
}
void cdog::callfunc()
{
cout << "汪汪叫" << endl;
}
int main()
{
ccattle cobj;
callfunc(&cobj);
cdog dobj;
callfunc(&dobj);
return 0;
}