-
子对象:类A的对象objA在类B做数据成员,将类B中的数据成员objA称为子对象
定义:
class A{
//类A的定义
};
class B{
private:
A objA;//子对象
int z;
}; -
使用子对象的目的:完成二次封装
#include<iostream>
using namespace std;
class A{
public:
void fun1()
{
cout<<"Class A fun()"<<endl;
}
};
class B{
private:
A objA;
public:
void fun2()
{
objA.fun1();
}
};
int main()
{
B objB;
objB.fun2();
return 0;
}
- 含子对象的类的构造函数表示
类名(总形参):子对象(实参)—>子对象的构造函数调用
{
表示非子对象数据成员的初始化;
};
含有子对象的类的构造调用:
①子对象调构造函数(子对象自己的)
②再执行自己的函数体
③含有子对象的析构函数的调用,严格与构造函数相反
#include<iostream>
using namespace std;
class A{
private:
int x,y;
public:
A(int x,int y)
{
this->x=x;
this->y=y;
}
void Print()
{
cout<<"x="<<x;
cout<<"y="<<y;
}
~A()
{
cout<<"!!!!!"<<endl;
}
};
class B{
private:
A objA;
int Z;
public:
B(int i):objA(i-2,i-1)//冒号及后面仅表示有无参数,有哪些参数,可省略表示,但调用不可省略
{
Z=i;
}
void Print()
{
cout<<Z<<endl;
}
~B()
{
cout<<"@@@@@"<<endl;
}
};
int main()
{
B objB(3);
objB.Print();
}
#include
using namespace std;
class A{
public:
A(){
cout<<“A cons”<<endl;
}
~A()
{
cout<<“A des”<<endl;
}
};
class B{
public:
B(){
cout<<“B cons”<<endl;
}
~B()
{
cout<<“B des”<<endl;
}
};
class C{
public:
C(){
cout<<“C cons”<<endl;
}
~C()
{
cout<<“C des”<<endl;
}
};
class D{
private:
C objC;
B objB;
A objA;
public:
D():objB()
{
cout<<“D cons”<<endl;
}
~D()
{
cout<<“D des”<<endl;
}
};
int main()
{
D objD;
}
特殊:i:在表示子对象的构造函数时,若无参,则可省略表示,但不可省略调用
调不调取决于类中有没有子对象,与:objA()无关
ii:若一个类中含有多个子对象,以定义顺序为每个子对象调用构造函数
#include<iostream>
using namespace std;
class A{
private:
int x,y;
public:
A()
{
x=0;
y=0;
cout<<"A cons"<<endl;
}
A(int x,int y)
{
this->x=x;
this->y=y;
cout<<"A cons"<<endl;
}
void Print()
{
cout<<"x="<<x<<",y="<<y<<endl;
}
~A()
{
cout<<"A des"<<endl;
}
};
class B{
private:
A objA;
int Z;
public:
B(int i,int j)
{
Z=i+j;
cout<<"B cons"<<endl;
}
B(){
Z=0;
cout<<"B cons"<<endl;
}
void Print()
{
objA.Print();
cout<<",Z="<<Z<<endl;
}
~B()
{
cout<<"B des"<<endl;
}
};
class C{
private:
B objB;
A objA;
public:
C(){}
C(int i):objA(i+3,i-1){}
void Print()
{
objB.Print();
objA.Print();
}
~C()
{
cout<<"C des"<<endl;
}
};
int main()
{
B myB(3,5);
C myC(4);
myB.Print();
myC.Print();
}