C++学习——类对象作为类成员与常函数

 类对象作为类成员

#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);
    

}

常对象只能调用常函数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值