类的对象作为其它类对象的成员变量
在类中如果需要其他对象作为成员函数时,需要注意以下几点:
1、 类中如果需要其他对象作为私有变量或者protected时,只能调用没有参数的构造函数
例如:
#include <iostream>
using namespace std;
class A
{
public:
A(char *p)
{
des = new char[10];
strcpy(des, p);
cout<<"OK2"<<endl;
}
A(){cout<<"BOK"<<endl;}
void show()
{
cout<<"hi"<<endl;
}
~A()
{
delete []des;
}
private:
char *des;
};
class B
{
public:
B()
{}
void show()
{
// a.show();
}
private:
A a("hi"); //若像此调用,会报错,改为A a,则成功编译
};
int main(void)
{
B *b = new B();
b->show();
delete b;
return 0;
}
2、若想在类中调用其它类的对象且带有参数的构造函数时,只能将其放入成员函数里对其进行调用,例如:
#include <iostream>
using namespace std;
class A
{
public:
A(char *p)
{
des = new char[10];
strcpy(des, p);
cout<<"OK2"<<endl;
}
A(){cout<<"BOK"<<endl;}
void show()
{
cout<<"hi"<<endl;
}
~A()
{
delete []des;
}
private:
char *des;
};
class B
{
public:
B()
{}
void show()
{
show1();
}
private:
void show1()
{
A a("hi");
}
};
int main(void)
{
B *b = new B();
b->show();
delete b;
return 0;
}