C++学习——成员函数与成员变量与this

成员变量和成员函数分开储存

空函数

#include <iostream>
using namespace std;
class Person {
public:
    //int old;

    Person() {
        cout << "默认无参" << endl;
    }

};
void test(){
    Person p;
    cout<<sizeof(p)<<endl;//编译器为空对象占用分配1字节,为了区分空对象占内存的位置
}
int main() {
    test();
    return 0;
}

非空函数 

#include <iostream>
using namespace std;
class Person {
public:
    int old;//非静态成员变量,内存属于类对象

    static int ed;//静态成员变量,内存不属于类对象

    //非静态成员函数,内存不属于类对象
    void funk(){
        cout<< 67 << endl;
    }

    //静态成员函数,内存属于类对象
    static void runk(){
    }

    Person() {
        cout << "默认无参" << endl;
    }

    ~Person(){
        cout<< "析构" <<endl;
    }

};
void test(){
    Person p;
    cout<<sizeof(p)<<endl;
}
int main() {
    test();
    return 0;
}

 

this

this概念

this是c++提供的特殊对象指针

this指向被调用的成员函数所指的对象

this指针隐含在每一个非静态成员函数内,不需要我们再去定义

this用途

当形参和成员变量同名时,可以用this指针来区分

Person(int old){
        old = old;
    }
Person(int old){
        this->old = old;
    }

 

在类的非静态成员函数中返回对象本身,可用return*this

#include <iostream>
using namespace std;
class Person {
public:
    int old;
    
    Person() {
        cout << "默认无参" << endl;
    }
    Person(int old){
        old = old;
    }

    ~Person(){
        cout<< "析构" <<endl;
    }
    
    Person& Add(Person &p){ 
        this->old+=p.old;
        return *this;
        
    }

};
void test(){
    Person p(10);
    Person p1(5);
    p.Add(p1).Add(p1);//链式编程
    cout<<sizeof(p)<<endl;
}
int main() {
    test();
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值