友元函数 & static explicit const 关键字「千字语法详解」

本文介绍了C++中的友元函数概念,包括友元函数对不同成员的访问权限,以及静态成员和常成员函数的特点。特别强调了friendclass声明和构造函数显式性的重要性。
摘要由CSDN通过智能技术生成

友元函数

example

#include <iostream>

using namespace std;

class Date {
public:
    Date(int _year, int _month, int _day) : year(_year), month(_month), day(_day) {}

    friend ostream& operator<<(ostream& out, const Date& d);

private:
    int year;
    int month;
    int day;
};

ostream& operator<<(ostream& out, const Date& d) {
    out << d.year << "/" << d.month << "/" << d.day << endl;
    return out;
}

int main() {
    Date d1(3, 5, 11);
    Date d2(2, 2, 2);
    cout << d1 << d2;
}

notion

  1. 友元函数可以访问私有(private)和受保护(protected)成员,但不能访问公有(public)成员。
  2. 友元函数不能用 const 进行修改。
  3. 一个函数可以被多个类声明为友元函数。

friend class

code

class Date;

class Time{
       friend class Date;
public:
      Time (){}
private:
int hour;
int min;
int sec;
};

class Date{
private:
int year;
int month;
int day;
Time _t;_
public:
void setTime(int _hour,int _min,int _sec){
_t.hour=_hour;
_t.min=_min;
 _t.sec=_sec;
}
};

notion

Class time 不能访问 Class Date,
但 Class Date 可以访问 Class Time;
Time->Date ERROR!
Date->Time AC!

the solution

class Date{
friend class Time;
......
}
;

Attention

friendship关系不能传递
如果A是B的友元,
B是C的友元;
但是C不是A的友元

static 成员变量

  1. 多个对象维护同一个类的static 成员函数
  2. 必须在类外定义类内声明,且类外不要加static 类内要;
  3. 脱离对象独立存在的要分配存储空间的

访问

  1. 对象名.静态成员名
  2. 类名.静态成员名
//init
int stu1.s=0;
int student:: s=0;

static 成员函数

  1. 静态成员函数才可以访问static成员变量
  2. 无this指针,所以不能用const 修饰
  3. 静态成员函数不能访问非静态成员函数和变量
  4. 不需要生出变量就能使用
  5. 类能直接访问static成员函数

Explicit

当你用"explicit"修改构造函数时,可以禁止函数的隐式转换。

Const

常成员函数

cosnt 修饰其this指针
*const this
不能修改成员变量
不能调用该类中没有用const 修饰的成员函数

常对象

  1. 不能调用任何类的成语函数,一旦定义,常对象就不能修改
  2. 只有类的常成员函数才可以访问该类的常对象,且const 成员函数不修改对象
  3. 不能修改
  4. 只能在定义是有构造函数初始化
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值