C+笔记6(内部类、内联函数、友元)


内部类

顾名思义在一个类中创建一个类。

#include<iostream>
using namespace std;
class People {
public:
	class Baby {//在类内定义使用
	public:
		int age;
	};
	Baby b;
};
int main() {
	People p;
	p.b.age = 1;
	People::Baby baby;//外部类名+作用域+内部类名
	return 0;
}

内联函数

创建内联函数的时候用inline关键词,在类中创建。

class People {
public:
    int money;
    inline void print() {
        cout << money << endl;
    }
};

内联函数的访问速度快(相当于宏函数),所以一般编写时建议:1.短小;2.使用频率高。

友元

友元函数

友元函数可以灵活地调整访问权限,但如果使用过多就会破坏类的封装性。

#include<iostream>
using namespace std;
class People {
private:
    int age;
public:
    void printAge() {
        cout << this->age << endl;
    }
    friend void printAge(); // 友元函数
    //friend int main();    //破坏了类的封装性
};
void printAge() {
    People p;
    cout << p.age << endl;
}
int main(){
    return 0;
}

友元类

class People {
private:
    int age;
public:
    void printAge() {
        cout << this->age << endl;
    }
    friend class Animal;
};
class Animal {
private:
    People p;
public:
    void printPeopleAge() {
        cout << p.age << endl;
    }
};

常函数(常成员函数)

在一个普通成员函数后面加上const修饰,就是常成员函数。常函数不能修改类属性,所以构造函数,静态成员函数,析构函数,全局成员函数都不能是常函数。

#include<iostream>
using namespace std;
class People {
private:
    int age;
public:
    void printAge() const{
        cout << age << endl;
        //age = 10;  //不能修改类属性
    }
};
int main(){
    People p;
    p.printAge();
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

du__kefeng

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值