今天摸鱼时间不算长,期末了,作业什么的比较多
C++友元函数以及友元类
友元函数
先直接给出性质:
- 类的友元函数定义在类外部,但有权访问类的所有私有(private)成员和保护(protected)成员。
- 尽管友元函数的原型有在类的定义中出现过,但是友元函数并不是成员函数。
- 如果要声明函数为一个类的友元函数,需要在类定义中该函数原型前使用关键字
friend。
下面是一个简单的例子:
#include <iostream>
using namespace std;
class person
{
public:
int score = 100;
void print();
friend void print2(person temp); //使用关键字friend
private:
string name = "hesorchen";
};
void person::print() //成员函数
{
cout << name << ' ' << score << endl;
}
void print2(person temp) //友元函数
{
cout << temp.name << ' ' << temp.score << endl;
}
int main()
{
person a;
a.print(); //成员函数
print2(a); //友元函数
return 0;
}
友元类
一个类 A 可以将另一个类 B 声明为自己的友元,类 B 的所有成员函数就都可以访问类 A 对象的私有成员。在类定义中声明友元类的写法如下:
friend class 类名;
例子:
#include <iostream>
using namespace std;
class person
{
public:
int score = 100;
void print();
friend void print2(person temp); //使用关键字friend
friend class dog;
private:
string name = "hesorchen";
};
void person::print() //成员函数
{
cout << name << ' ' << score << endl;
}
void print2(person temp) //友元函数
{
cout << temp.name << ' ' << temp.score << endl;
}
class dog //友元类
{
public:
int age;
void print(person a)
{
cout << "Owner is:" << a.name << endl; //可以访问person类的private成员变量name
}
private:
string name;
};
int main()
{
person a;
dog b;
a.print(); //成员函数
print2(a); //友元函数
b.print(a);
return 0;
}
先来简单说一下static修饰的静态变量
static修饰的变量,仅在第一次执行该语句时初始化,之后不再初始化。他的内存被分配在全局数据区中,但是作用域在局部作用域。
静态数据成员以及静态成员函数
静态数据成员
类的静态数据成员比较复杂,总结几点比较重要的性质吧
1.静态数据成员在类中只能声明不能定义,要对其进行定义只能在全局作用域中定义
2.静态数据成员不属于任何对象,它被类的所有对象共享,包括派生类
class person
{
public:
string name;
int age;
static int score; //声明
};
int person::score = 1; //定义
/*
int Class::a=10;
数据类型+类名+作用域符号+变量名=10;
*/
#include <iostream>
using namespace std;
class person
{
public:
string name;
int age;
static int score; //声明
};
int person::score = 1; //定义
class teacher : public person
{
};
int main()
{
person a, b;
teacher c;
cout << teacher::score << endl;
cout << a.score << ' ' << b.score << ' ' << c.score << endl;
a.score++;
cout << a.score << ' ' << b.score << ' ' << c.score << endl;
/*
Output:
1
1 1 1
2 2 2
*/
return 0;
}
静态成员函数
与静态数据成员相类似地有:
1.定义方式相似
2.属于类而不属于对象
3.静态成员函数不属于某个对象,自然也就不存在this指针
示例:
#include <iostream>
using namespace std;
class person
{
public:
string name;
int age;
static void print(); //声明
};
void person::print() //定义
{
cout << "hello world!" << endl;
}
int main()
{
person::print();
person a;
a.print();
return 0;
}
今天个人觉得还算充实,不过还是有任务拖欠到了明天,而且没早睡… …
本文深入探讨了C++中的友元函数和友元类的概念,通过实例展示了如何利用友元特性访问类的私有成员。同时,文章详细解释了静态数据成员和静态成员函数的特点与应用,包括它们的定义、作用域以及与类对象的关系。
280

被折叠的 条评论
为什么被折叠?



