C+ 类 常量函数、友元函数、单例

  1. 常量函数 表示不允许修改类中的成员
int i,j  //类中的成员
void Student::set(int j) const {
	this->j = j;  // 错误
    cout<<i<<endl;  // 正确
}
  1. 友元函数
    在定义一个类的时候,可以把一些函数(包括全局函数和其他类的成员函数)声明为“友元”或一些类声明为友元,这样这些函数就成为该类的友元函数,在友元函数内部就可以访问该类对象的私有成员了。
friend void set(Student* stu); // 友元函数 在该函数内部可以访问Student类的私有变量
class Student {
    friend void set(Student* stu);
    friend class Friend; // 友元类 在该类中可以访问Student的私有变量
};
  1. 单例
class Runtime {
private:
    static Runtime* instance;
    Runtime();
public:
    static Runtime* getInstance();
};

#include "Runtime.hpp"
Runtime::Runtime(){
}
Runtime* Runtime::instance = 0;
Runtime* Runtime::getInstance() {
    if (!instance) {
        instance = new Runtime();
    }
    return instance;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值