内部类
顾名思义在一个类中创建一个类。
#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;
}