zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    AcWing 1059. 股票买卖 VI Leetcode714. 买卖股票的最佳时机含手续费 dp
    AcWing 1058. 股票买卖 V Leetcode309. 最佳买卖股票时机含冷冻期
    Js取float型小数点后两位数的方法
    浏览器退 事件
    微信中得到的GPS经纬度放在百度,腾迅地图中不准的原因及处理
    dropdownlist 控件的判断
    有一个无效 SelectedValue,因为它不在项目列表中。
    CSS从大图中抠取小图完整教程(background-position应用)
    去掉 input type="number" 右边图标
    页面中星号与字体对齐
  • 原文地址:https://www.cnblogs.com/yocichen/p/11110628.html
Copyright © 2011-2022 走看看