• C++ 类再探


    关于类的一些遗漏的点。

     1 #include <iostream>
     2 #include <typeinfo>
     3 #include <string>
     4 using namespace std;
     5 
     6 class Person {
     7     //设为友元,可访问类的非公有成员
     8     friend void read(istream &is, Person &p);
     9     friend void print(ostream &os, Person &p);
    10 private:
    11     string name;
    12     string address;
    13     mutable int count = 0;//突破界限之const函数改值
    14 
    15 public:
    16     static string t;
    17     Person() = default;
    18     Person(string _name, string _address) {
    19         name = _name;
    20         address = _address;
    21     }
    22     string getName() const {
    23         ++ count;//mutable 可变值
    24         t = "blue"; //static 也可变
    25         return this->name;
    26     }
    27     string getAddress() const {
    28         return this->address;
    29     }
    30     int getCount() const {
    31         return this->count;
    32     }
    33 };
    34 
    35 string Person::t = "yellow";
    36 
    37 //read the obj
    38 void read(istream &is, Person &p)
    39 {
    40     is >> p.name >> p.address;
    41 }
    42 
    43 //print the obj
    44 void print(ostream &os, Person &p) 
    45 {
    46     os << p.name << " " << p.address;
    47 }
    48 
    49 int main()
    50 {
    51     Person yoci("nan", "Shan'an-Xi");
    52     cout << yoci.getName() << endl;
    53     cout << yoci.getAddress() << endl;
    54     cout << yoci.getCount() << endl;
    55     cout << Person::t << endl;
    56 
    57     return 0;
    58 }

    总结:

    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

  • 相关阅读:
    table-layout:fixed 布局注意事项
    resize 按钮不会被伪元素遮盖
    background-size:100% 100% 时 background-position: % 失效
    利用 background 和 filter 模糊指定区域
    window.location.href = window.location.href 跳转无反应 a 超链接 onclick 点击跳转无反应
    如何在前台脚本通过json传递数据到后台(使用微软自带的ajax)
    .clear 万能清除浮动
    个人博客开通了
    Mysql The user specified as a definer ('test'@'%') does not exist
    MERGE INTO 解决大数据量复杂操作更新慢的问题
  • 原文地址:https://www.cnblogs.com/yocichen/p/11110628.html
Copyright © 2020-2023  润新知