类对象作为类成员
#include<iostream>;
using namespace std;
class cat{
public:
int num;
cat(int num){
this->num = num;
cout<< "cat的有参构造 "<<endl;
}
cat() {
cout<< "cat的默认无参" <<endl;
}
~cat(){
cout<< "cat的析构函数" <<endl;
}
};
class Person{
public :
int old;
cat ou;
Person(){
cout<< "默认无参 "<<endl;
};
Person(int old, int num){
this->old = old;
ou.num = num;
cout<< "Person的有参构造 "<<endl;
}
~Person() {
cout<< "person的析构函数" <<endl;
}
};
void test(){
Person p(2,3);
}
int main(){
test();
return 0;
}
cat的默认无参
Person的有参构造
person的析构函数
cat的析构函数
其他类作为本类对象时,构造时先构造其他类,再构造本类,析构相反
常函数
在成员对象后加const实际上修饰的是this指针
void test01(){
this->old = 100;
this = NULL;
}
this的本质是一个常量指针,不能修改指向
void test01() const
{
//this->old = 100;
}
加const修饰后,实际转换为const Person *const this
也不能修改所指对象的值
mutable
int old;
mutable int num;//特殊变量,即使是在常函数中也可以修改,所指向的值
void test01() const
{
//this->old = 100;
this->num = 100;
}
常对象
void test(){
const Person p(12, 23);
}
常对象只能调用常函数