一、包含关系
当一个类构建的对象为另一个类的成员对象时:
当一个类型包含另一个对象时,本类没有构造,析构,拷贝,赋值,但成员类有这些函数,本类就可以进行自己的合成因此来调动成员对象的函数。要和成员对象的行为保持一致。
class Object
{
int value;
public:
Object(int x = 0) :value(x)
{
cout << "构建" << this << endl;
}
~Object()
{
cout << "析构" << this << endl;
}
Object(const Object& obj) :value(obj.value)
{
cout << "Object::拷贝" << this << endl;
}
Object& operator=(const Object& obj)
{
if (this != &obj)
{
value = obj.value;
}
cout << "Object::赋值" << this << endl;
return *this;
}
};
class Base
{
int num;
Object obj;
public:
Base(int x = 0) :num(x),obj(x) //若是没有会进行合成,以下同理
{
cout << "构建" << this << endl;
}
~Base()
{
cout << "析构" << this << endl;
}
Base(const Base& base) :num(base.num),obj(base.obj)
{
cout << "Object::拷贝" << this << endl;
}
Base& operator=(const Base& base)
{
if (this != &base)
{
num = base.num;
obj = base.obj;
}
cout << "Base::赋值" << this << endl;
return *this;
}
};
int main()
{
Base base1(10);
Base base2(base1);
Base base3;
base3 = base1;
return 0;
}
二、继承关系
当一个类继承另一个类时:
拷贝构造:
①无论基类写或不写拷贝或赋值函数,子类没写时都会进行合成,(注意若子类写了拷贝函数,在调用基类的拷贝构造,要写明(Object(base)))
②基类没有拷贝函数,子类有拷贝函数。不可以让父进行合成,只能调动构造函数来创建base2的隐藏父对象。
即:对于拷贝构造函数来说,基类可以约束子类进行合成,反过来,子类不能约束基类进行合成
赋值函数
①基类没有,子类也没有:正常赋值,将base1的值全部给base3。
②基类没有,子类有:只能赋值子对象的成员属性。
③基类有,子类没有:会约束子类产生赋值语句,正常赋值,基类和父类对象的属性都会赋值。
④基类有,子类也有:子类的赋值语句无法调动父类的赋值语句,只能赋值子对象的成员属性。
class Object
{
int value;
public:
Object(int x = 0) :value(x)
{
cout << "构建" << this << endl;
}
~Object()
{
cout << "析构" << this << endl;
}
Object(const Object& obj) :value(obj.value)
{
cout << "Object::拷贝" << this << endl;
}
Object& operator=(const Object& obj)
{
if (this != &obj)
{
value = obj.value;
}
cout << "Object::赋值" << this << endl;
return *this;
}
};
class Base:public Object
{
int num;
public:
Base(int x = 0) :num(x),Object(x)
{
cout << "构建" << this << endl;
}
~Base()
{
cout << "析构" << this << endl;
}
Base(const Base& base) :num(base.num),Object(base)
{
cout << "Object::拷贝" << this << endl;
}
Base& operator=(const Base& base)
{
if (this != &base)
{
num = base.num;
}
cout << "Base::赋值" << this << endl;
return *this;
}
};
int main()
{
Base base1(10);
Base base2(base1);
Base base3;
base3 = base1;
return 0;
}