学习目标
常函数、常对象、友元成员函数、友元类,这些关键知识不容错过,学习刻不容缓!!!
学习内容
💖常函数: 用const修饰成员函数时,const修饰this指针的内存区域,成员函数内不能修改任何本类内的普通成员变量
但是被mutable修饰的成员变量除外
💖常对象: 用const修饰的创建的对象,常对象不允许调用对象成员与普通函数,但是被mutable修饰的成员变量除外
💖友元:
友元三种种类:
1、友元(全局)函数
2、友元类
3、友元成员函数
这里只是简单的介绍了一下,具体学习下面代码就可以更深入的了解
学习代码
🎈常函数和常对象的使用,基础使用,看完加深理解!!
#include<iostream>
using namespace std;
class Person
{
public:
int age;
mutable int height;
Person() {
}
Person(int age) {
this->age = age;
}
void func() const{//常函数
//this->age = 100;常函数不能对成员变量进行修改,但对mutable修饰的除外
this->height = 183;
cout << age << endl;
cout << height << endl;
}
void func1() {
}
};
int main() {
Person p(2);
p.func();
const Person p1(3);//常对象
p1.func();
//p1.age = 1;//常对象不允许调用对象成员与普通函数
//p1.func1();
p1.height = 100;//常对象可以对mutable变量进行修改
return 0;
}
🎈友元函数
#include<iostream>
#include<string>
using namespace std;
class building {
friend void fangwen(building& b1);
private:
string m_bedroom;
public:
string m_sittingroom;
building() {
m_sittingroom = "客厅";
m_bedroom = "卧室";
}
};
void fangwen(building &b1) {
cout << "访问" << b1.m_sittingroom << endl;
cout << "访问" << b1.m_bedroom << endl;
}
int main() {
building b1;
cout << "访问" << b1.m_sittingroom << endl;
//cout << "访问" << b1.m_bedroom << endl;
fangwen(b1);
return 0;
}
🎈友元类
#include<iostream>
#include<string>
using namespace std;
class Building;
class Building {
friend class Goodfriend;
private:
string m_bedroom;
public:
string m_sittingroom;
void fangwen();
};
void Building::fangwen() {
m_sittingroom = "客厅";
m_bedroom = "卧室";
cout << "访问" << m_sittingroom << endl;
cout << "访问" << m_bedroom << endl;
}
class Goodfriend {
public:
void getbuilding(Building& b);
};
void Goodfriend::getbuilding(Building& b) {
cout << "访问" << b.m_sittingroom << endl;
cout << "访问" << b.m_bedroom << endl;
}
int main() {
Building b1;
Goodfriend gf;
b1.fangwen();
gf.getbuilding(b1);
return 0;
}
🎈友元成员函数
#include<iostream>
#include<string>
using namespace std;
class Building;
class Goodfriend {
public:
void visit(Building& b);
};
class Building {
friend void Goodfriend::visit(Building& b);//友元成员函数
private:
string m_bedroom;
public:
string m_sittingroom;
void fangwen();
};
void Building::fangwen() {
this->m_sittingroom = "客厅";
this->m_bedroom = "卧室";
}
void Goodfriend::visit(Building& b) {
cout << "访问:" << b.m_sittingroom<< endl;
cout << "访问:" << b.m_bedroom << endl;
}
int main() {
Building b1;
Goodfriend gf1;
b1.fangwen();
gf1.visit(b1);
return 0;
}
代码实现
🧨常函数和常对象
🧨友元函数
🧨友元类
🧨友元成员函数