http://stackoverflow.com/questions/1501920/base-copy-constructor-not-called
//有关C++的构造以及析构的经典总结(constructor,copy constructor,operator=,destructor):
/*
1)首先对于nontrivial的类(即有virtual method,vtable等),不管你写(自定义)或是没写(default)
copy control,constructor,destructor,编译器都会为你添加一些代码.
2)对于copy control,constructor,destructor:若是自定义写了它们,编译器就不会生成default版本
了,但1)的代码仍旧是给你添进去的. (所以有写在private:里面这种机制)
3)constructor,destructor有栈调用默认机制;copy constructor,operator=没有,所以此两者要显式
地去调用基类的copy constructor以及operator=.
*/
enum color{
red,
yellow,
green
};
int b[3]={3,2,1};
int (&p)[3]=b;
class CShape{
public:
//凡是有virtual函数的类,就说明它会被多态,所以它的destructor最好也是virtual的
virtual ~CShape(){}
//rule of three
CShape(const char* p){
this->shapeName=p;
}
CShape(const CShape& p){
shapeName=p.shapeName;
}
CShape& operator= (const CShape& p){
if(this==&p)
return *this;
shapeName=p.shapeName;
}
//virtual(not pure)是继承接口以及缺省行为
virtual void show();
//pure virtual是只继承接口
//接口继承
virtual void draw()=0;
//非虚拟函数的目的是让derived class继承接口以及实现
//实现继承
void shapeShow();
void setShapeName();
//static管它是不是abstract class,照样可以使用CShape::showP函数
static void showP()
{
cout<<p[0]<<" "<<p[1]<<" "<<p[2]<<" "<<endl;
}
private:
string shapeName;
};
void CShape::show(){
cout<<this->shapeName<<endl;
}
void CShape::shapeShow()
{
cout<<this->shapeName<<endl;
}
void CShape::setShapeName(){
shapeName="hello";
}
class Rectangle:public CShape{
public:
virtual ~Rectangle(){}
Rectangle(const char *p):CShape("SHAPE"),rectName(p){
//enum的使用
//color rectColor=red;
}
//显式调用基类的copy constructor,operator=
Rectangle(const Rectangle& p):CShape(p){
rectName=p.rectName;
}
Rectangle& operator= (const Rectangle& p){
if(this==&p)
return *this;
CShape::operator =(p);
rectName=p.rectName;
}
virtual void draw();
virtual void show();
//即static method不可以操作nonstatic member,只能操作static member
//但是倒过来,nonstatic method可以操作static member
/*
static void sprint(){
cout<<"shape:"<<shapeshow();
cout<<"rect:"<<show();
}
*/
void print(){
cout<<"shape:";
shapeShow();
cout<<"rect:";
show();
}
private:
string rectName;
};
void Rectangle::draw(){
cout<<"rectangle drawing"<<endl;
}
void Rectangle::show(){
cout<<this->rectName<<endl;
}
#endif // CSHAPE_H