组合:我们简单地在新类中创建已存在类的对象,因为新类是由已存在类的对象组合而成。
构造函数的初始化表达式表允许我们显式地调用成员对象的构造函数
构造函数和析构函数不能被继承
operator=也不能被继承
私有继承
#include<iostream>
using namespace std;
class A{
public:
void f(){}
};
class B:A{//default private
public://need public
using A::f;//no ()
};
int main()
{
B b;
b.f();
}
关于初始化顺序
#include<iostream>
using namespace std;
class Parent{
int i;
public:
Parent(int ii):i(ii){
cout << "Parent(int ii)\n";
}
Parent(const Parent& b):i(b.i){
cout << "Parent(const Parent&)\n";
}
friend ostream& operator<<(ostream& os,const Parent& b){
return os<<"Parent:" << b.i << endl;
}
};
class Member{
int i;
public:
Member(int ii):i(ii){
cout << "Member(int ii)\n";
}
Member(const Member& m):i(m.i){
cout << "Member(const Member&)\n";
}
friend ostream& operator<<(ostream& os,const Member& m){
return os<< "Member:" << m.i << endl;
}
};
class Child:public Parent{
int i;
Member m;
public:
Child(int ii):Parent(ii),i(ii),m(ii){
cout << "Child(int ii)\n";
}
Child(const Child& c):Parent(c.i),i(c.i),m(c.i){
cout << "Child(const Child&)\n";
}
friend ostream& operator<<(ostream& os,const Child& c){
return os << (Parent&)c << c.m << "Child:" << c.i << endl;
}
};
int main(){
Child c(2);
cout << "Calling copy-constructor:" << endl;
Child c2 = c;
cout << "values in c2:\n" << c2;
}
输出:
Parent(int ii)
Member(int ii)
Child(int ii)
Calling copy-constructor:
Parent(int ii)
Member(int ii)
Child(const Child&)
values in c2:
Parent:2
Member:2
Child:2