For Lab1.

Here is an example to write and use a cpp class.

#include 
#include 
using namespace std;

class Range 
{
   private:
      float hight;
      float weight;
      string name;
   public:
      void set_hight(float);
      void set_weight(float);
      void set_name(string);

      float get_hight() const;
      string get_name() const;
};
void Range::set_hight(float tmp)
{
   hight=tmp;
}
void Range::set_weight(float tmp)
{
   weight=tmp;
}
void Range::set_name(string tmp)
{
   name=tmp;
}
float Range::get_hight() const
{
   return hight;
}
string Range::get_name() const
{
   return name;
}

int main(void)
{
   Range zzx;
   zzx.set_hight(179);
   zzx.set_weight(150);
   zzx.set_name("zzx1024");
   cout << zzx.get_hight() <<endl;
   cout << zzx.get_name() <<endl;
   return 0;
}

In fact, it is better to declare this class in a separate cpp header file.

The symbol ‘::’ is called ‘作用域解析运算符’。

So we need to change it into this form

#ifndef RANGE00_H_
#define RANGE00_H_

#include <string.h>

/*  class .........  */

#endif

to make sure the header is added only once.

Object Oriented Programming is quite new for me. I also learned more about it.

对象是程序的基本单元,包括数据成员和函数(属性和方法)。

类是对客观事物的抽象,本质是一种数据类型,实例为对象。

面向对象的思路侧重于将问题抽象和封装,软件的顶层架构设计。

面向对象的三大特征为 封装,继承,多态。

分别为

将客观事物抽象为类,也就是属性和方法。

子对象有父类对象的属性和方法。

一个接口的多种实现,覆盖和重载

我们在上文已经实现了封装一个class,下面尝试一下新建一个class然后继承已有的class

class child_R:private Range
{
   private:
      int fine;
};

这样child_R就会继承 Range 当中的private。

因为private是无法在外部访问,所以如果继承父类private,你无法使用父类指针指向子类地址。

但是可以在自建函数访问父类函数,比如

重载和覆盖难度也比较好解释。

比如上文中Range当中已经有void set_weight(float);的定义,当我们再次在child_public中声明void set_weight(float);, vs code表示找不到,所以可见实际上是被覆盖掉了。

如果我们同时声明函数,名称一样,但是参数不一样,依然可以通过参数的不同来决定是哪一个重载。

如图,会尝试从指定类型匹配找合适的重载函数。

这一次先写这些,虚函数后续再学习。

Views: 103

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.