类与结构体(5)

上期我们提到了这一期讲“类该怎么用?(2)/(3)”。

类该怎么用?(2)—— 友元函数

        类的友元函数不创建在类里,但他可以访问private,protected。友元函数要先在类里面声明,但是友元函数不是类的成员函数

友元可以表示为:

#include <bits/stdc++.h>
using namespace std;
class student{
private:
    string name;
    int age, finalexam;
public:
    friend bool operator<(const student &Student, const student &test);
};
int main(){

    return 0;
}

这是友元函数;下一个我们来看友元类:

#include <bits/stdc++.h>
using namespace std;
class student{
private:
    string name;
    int age, finalexam;
public:
    friend bool operator<(const student &Student, const student &test);
    friend class nextStudent;
};
int main(){

    return 0;
}

在这里nextStudent可以访问student的私有成员函数,也就是name,age,finalexam。

(可看可不看)类该怎么用?(3)—— 构造函数初始化列表

我们来看一下吧,其实不说那么深奥就为了省代码:

就是一个构造函数(之前讲过);

class student{
public:
    string name;
    int age, finalexam;
    student() : name("xiaoming"), age(18), finalexam(100){}
};

这个构造函数就是为了初始化,这里不能用name = "xiaoming"这个要编译错误。

下期预告:

下期我们讲类的继承,存储类。(难度较大)

相关推荐

  1. 结构5

    2024-02-13 15:08:01       51 阅读
  2. 结构(4)

    2024-02-13 15:08:01       51 阅读
  3. C++基础——结构

    2024-02-13 15:08:01       34 阅读
  4. C++ 结构

    2024-02-13 15:08:01       49 阅读
  5. C# 结构

    2024-02-13 15:08:01       38 阅读
  6. QT-结构

    2024-02-13 15:08:01       30 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-13 15:08:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-13 15:08:01       101 阅读
  3. 在Django里面运行非项目文件

    2024-02-13 15:08:01       82 阅读
  4. Python语言-面向对象

    2024-02-13 15:08:01       91 阅读

热门阅读

  1. 新能源+AI未来的大趋势

    2024-02-13 15:08:01       51 阅读
  2. 网络安全漏洞管理十大度量指标

    2024-02-13 15:08:01       46 阅读
  3. python推导式

    2024-02-13 15:08:01       46 阅读
  4. 使用 C++23 从零实现 RISC-V 模拟器

    2024-02-13 15:08:01       54 阅读
  5. onnx基础

    2024-02-13 15:08:01       51 阅读
  6. QShortcut

    2024-02-13 15:08:01       58 阅读
  7. c# Avalonia 伪类 Pseudo Classes 改变样式

    2024-02-13 15:08:01       49 阅读
  8. 【Python】洛谷P7614 [COCI2011-2012#2] NAJBOLJIH 5

    2024-02-13 15:08:01       53 阅读
  9. LeetCode1143. Longest Common Subsequence——动态规划

    2024-02-13 15:08:01       45 阅读
  10. PMP-情景模拟学习法-识别项目阶段

    2024-02-13 15:08:01       54 阅读
  11. 合适的用例-《软件方法》自测题解析035

    2024-02-13 15:08:01       64 阅读
  12. MySQL进阶查询篇(9)-视图的创建和应用

    2024-02-13 15:08:01       46 阅读
  13. 苍穹外卖面试题

    2024-02-13 15:08:01       48 阅读