C++入门篇十三

常对象: const  Person p1;

不可以调用普通成员函数,除非前面加了函数前面加了const
可以调用常函数
在对象之前加入const修饰 const Person p1;

常函数:void func()  const{}

void func() const {} 修饰的是this指针 const Type * const this
不能修改this指针指向的值,age本质上就是this->age,所以不能修改

// 对象.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include "pch.h"
#include <iostream>
using  namespace  std;


//常函数和常对象
class  Person {
public:
    Person() {
        //构造中修改属性
        //当前对象做的值操作

    }


    //普通成员函数
    void  show() {

    }
    //常函数
    void  showinfo() const {//加了const是不允许修改的
        //常函数不允许修改
        //this->m_A = 32;
        this->m_B = 43;//这个是可以修改的,下面是加了mutable
        cout << "m_a:" << this->m_A << "m_b" << this->m_B << endl;
    }
    //这个是不可以常函数const修改的,this->m_A
    int m_A;
    //这个是常函数可以修改的
    mutable  int  m_B;//就算是常函数,还是可以执意修改的,mutable

};

void  test01() {
    Person  p1;
    p1.showinfo();
    p1.m_A = 332;

    //如果是常对象的话,不允许修改属性,但是读是可以的
    const  Person  p2;
    //p2.m_A = 434;//读是可以的,写是不可以的
    p2.showinfo();//showinfo是常函数,但是show是普通成员函数
}

int main() {

    test01();
}

 

 

友元函数:friend,可以设置是可以访问私有权限的,谁是不可以访问私有权限的

#include "pch.h"
#include <iostream>
using  namespace  std;
#include<string>

class   Building {
    friend  void   You(Building  *building);//把下面的函数声明加进来,在加上一个关键字friend就是友元函数
public:
    Building(){
        //默认构造
        this->centerroom = "客厅";
        this->bedroom = "卧室";
    }

public:
    string    centerroom;
private:
    string    bedroom;

};

void   You(Building  *building) {//传过来的是地址,Building  *building=&实例对象
    cout << "好友访问" << building->bedroom << endl;
    cout << "好友访问" << building->centerroom << endl;

};

void  test01() {
    Building  *p1 = new  Building;
    You(p1);//传了一个地址过去
}


int main() {
    test01();

}

 

猜你喜欢

转载自www.cnblogs.com/yunxintryyoubest/p/10687384.html