1. C++ 类&对象

2020-10-10  本文已影响0人  开源519

1.简介

C++的用法非常复杂,不仅兼容C语法,还包括其他语法以及自身的语法风格。由于工作需要,本人也开始涉及C++的学习。本着从易到难的学习过程,在学习C++的过程中与C语言对比,形成自己的C++面向对象思想编程的风格。

类是C++面向对象思想编程的基准,也把C++面向对象编程称为类编程。定义一个类,其中包括一些变量,以及操作函数(类似于C语言struct结构体中的变量成员和函数指针成员)。

E.g.

class Student
{
   public:
      char gender;   //学生的性别
      char name;     // 学生的名字
      char years;     // 学生的年龄
      char height;    // 学生的身高
      char weight;   // 学生的体重

  private:
       char rank;    // 学生的名次
};

C++使用class定义类名,默认成员为private类型。public、private以及protected关键字可设置类成员访问属性,其中在类作用域中,public声明的成员可直接访问。

定义对象

类是定义对象的基础,当类建立完毕后,就可像数据类型一样声明对象。声明的对象属于包含类的所有成员。(类似于C语言struct声明数据结构)

Student stu1;  //声明stu1, 类型Student
Sudent stu2;   //声明stu2, 类型Student

类成员访问

既然声明了对象,自然其对象包含的成员也可以访问。

#include <iostream>
 
using namespace std;

class Student
{
   public:
      int years;     // 学生的年龄
      int height;    // 学生的身高
      int weight;   // 学生的体重

   private:
      int rank;    // 学生的名次
};

int main()
{
    Student stu1;  //声明stu1, 类型Student
    Student stu2;   //声明stu2, 类型Student

    stu1.years = 12;
    stu1.height = 140;
    stu1.weight = 80;
    
    stu2.years = 12;
    stu2.height = 130;
    stu2.weight = 75;
    
    cout <<"stu1: " << " years " << stu1.years << " height " << stu1.height << " weight " << stu1.weight <<endl;
    cout <<"stu2: " << " years " << stu2.years << " height " << stu2.height << " weight " << stu2.weight <<endl;
    
    return 0;
}

输出

stu1:  years 12 height 140 weight 80
stu2:  years 12 height 130 weight 75

总结

  1. 在C++类成员类型声明中,如果声明的是char型,就默认以字符型打印,因此在赋予整型值时,打印会与设想的有出入。就类似于C语言中的char类型用%d与%c打印的区别,在C++中char型,cout默认按%c打印。

  2. 虽然之前也掌握本篇记录的内容,但既然选择重新学习C++,那就从最基础的地方做起并记录。一步一个脚印,直到掌握。

后记

本人对于C++的学习,主要是按着 C++ 菜鸟教程 走。个人觉得菜鸟教程上的解析比教通俗易懂,在学习的时候将这些例子也会记录下来方便日后移动端随时查阅。

上一篇 下一篇

猜你喜欢

热点阅读