C++ 类再探
2024-08-27 10:03:22
关于类的一些遗漏的点。
#include <iostream>
#include <typeinfo>
#include <string>
using namespace std; class Person {
//设为友元,可访问类的非公有成员
friend void read(istream &is, Person &p);
friend void print(ostream &os, Person &p);
private:
string name;
string address;
mutable int count = ;//突破界限之const函数改值 public:
static string t;
Person() = default;
Person(string _name, string _address) {
name = _name;
address = _address;
}
string getName() const {
++ count;//mutable 可变值
t = "blue"; //static 也可变
return this->name;
}
string getAddress() const {
return this->address;
}
int getCount() const {
return this->count;
}
}; string Person::t = "yellow"; //read the obj
void read(istream &is, Person &p)
{
is >> p.name >> p.address;
} //print the obj
void print(ostream &os, Person &p)
{
os << p.name << " " << p.address;
} int main()
{
Person yoci("nan", "Shan'an-Xi");
cout << yoci.getName() << endl;
cout << yoci.getAddress() << endl;
cout << yoci.getCount() << endl;
cout << Person::t << endl; return ;
}
总结:
1. 友元函数和友元类:在类内部声明友元(在该函数/类前加上friend即可),友元可以访问非公有成员在内的所有成员;
2. mutable 关键字,界限突破。声明mutable 变量,该变量一直处于可改变状态,就算在const函数内,照该不误;
3. 默认生成构造函数 ClassName() = default;为该类生成默认构造函数;
4. 删除函数:func() = delete; 禁止实现该函数;
5. 静态成员:
(1)静态数据成员:static声明,属于类而非对象,所有对象共享该变量可以使用 作用域运算符:: 对象. 成员函数 三种方法访问。
(2)静态函数成员:不包含this指针,不可声明为const,不能访问非静态成员(需要this指针,而它没有)
6.静态数据成员和一般成员的区别:
(1)不专属于谁,属于大家(所有对象);
(2)类外初始化;
(3)可用做默认参数
(4)可以是所属类 类型
(5)const函数内部仍可改值(就像加了mutable一样)
(6)访问方式:不能使用this->来访问。
参考资料:
【1】https://www.cnblogs.com/qionglouyuyu/p/4620401.html
最新文章
- java 中时间的比较 用compareTo方法
- adv
- 2016 icpc-ec-final
- linux:nohup 不生成 nohup.out的方法
- Python学习笔记——文件写入和读取
- Emacs简易教程
- iOS开发——UI篇Swift篇&;UITextView
- java程序:set改造成map
- SSH没有password安全日志
- liunx 系统调用 getopt() 函数
- sendGrid 纯文本的换行问题
- 我是如何将网站全站启用Https的?-记录博客安装配置SSL证书全过程
- IntelliJ IDEA下SVN的配置及使用说明
- codeforces733C
- PTA编程总结2—币值转换
- vue学习_01
- IBM 3650 M3 yum upgrade后系统无法登陆问题
- .NET基础之构造函数
- 论文阅读笔记:【MDNet】
- Codeforces 251C Number Transformation