类和对象

简介: 类和对象

1.什么是类和对象

(1)类是一种用户定义的引用数据类型,也称类类型,类是由对象总结而来的,总结的这个过程叫做抽象


(2)对象 : 类的一种具象,对象是由类具体实施出来的,这个过程叫做实例化


2.对象和类的关系

类与对象的关系就如模具和铸件的关系,类的实力化的结果就是对象,而对对象的抽象就是类,类描述了一组有相同特性(属性)和相同行为的对象。


3.类和结构体的区别

  • 结构体是值类型,类是引用类型
  • 结构体存在栈中,类存在堆中
  • 结构体成员不能使用protected访问修饰符,而类可以
  • 结构体成员变量申明不能指定初始值,而类可以
  • 结构体不能申明无参的构造函数,而类可以
  • 结构体申明有参构造函数后,无参构造不会被顶掉
  • 结构体不能申明析构函数,而类可以
  • 结构体不能被继承,而类可以
  • 结构体需要在构造函数中初始化所有成员变量,而类随意
  • 结构体不能被静态static修饰(不存在静态结构体),而类可以

4.代码理解

(1)第一种写法

#include <stdio.h>
 
//类:抽象 模板
struct Animal
{
  char name[128];
  int age;
  int sex;
  
  void (*peat)();
  void (*pbeat)();
};
 
void dogEat()
{
  printf("dog eat\n");
}
 
void catEat()
{
  printf("cat eat\n");
}
 
void personEat()
{
  printf("person eat\n");
}
 
void dogBeat()
{
  printf("dog beat\n");
} 
 
void catBeat()
{
  printf("cat beat\n");
} 
 
void personBeat()
{
  printf("person beat\n");
} 
 
 
int main()
{
  struct Animal dog;
  struct Animal cat;
  struct Animal person;//对象:事物的具象
  
  dog.peat = dogEat;
  cat.peat = catEat;
  person.peat = personEat;
  
  dog.pbeat = dogEat;
  cat.pbeat = catEat;
  person.pbeat = personEat;
  
  dog.peat();
  cat.peat();
  person.peat();
  
  dog.pbeat();
  cat.pbeat();
  person.pbeat();
  return 0;
}

(2)第二种写法(结构体新写法)

#include <stdio.h>
 
//类:抽象 模板
struct Animal
{
  char name[128];
  int age;
  int sex;
  
  void (*peat)();
  void (*pbeat)();
};
 
void dogEat()
{
  printf("dog eat\n");
}
 
void catEat()
{
  printf("cat eat\n");
}
 
void personEat()
{
  printf("person eat\n");
}
 
void dogBeat()
{
  printf("dog beat\n");
} 
 
void catBeat()
{
  printf("cat beat\n");
} 
 
void personBeat()
{
  printf("person beat\n");
} 
 
 
int main()
{
  struct Animal dog = {
    .peat = dogEat,
    .pbeat = dogBeat
  };
  
  struct Animal cat = {
    .peat = catEat,
    .pbeat = dogBeat
  };
  
  struct Animal person = {
    .peat = personEat,
    .pbeat = personBeat
  };
  
  dog.peat();
  cat.peat();
  person.peat();
  
  dog.pbeat();
  cat.pbeat();
  person.pbeat();
  return 0;
}
相关文章
|
1月前
|
编译器 C语言 C++
c++类和对象
c++类和对象
30 1
|
1月前
|
编译器 C# C++
【C++】类和对象(四)
【C++】类和对象(四)
|
8月前
|
存储 安全 编译器
【C++】类和对象(中)(二)
【C++】类和对象(中)(二)
【C++】类和对象(中)(二)
|
1月前
|
Java 编译器 Linux
C++:类和对象(下)
C++:类和对象(下)
35 1
|
1月前
|
编译器 C++
【C++】:类和对象(3)
【C++】:类和对象(3)
41 0
|
7月前
|
存储 编译器 C语言
类和对象(一)
类和对象(一)
|
8月前
|
编译器 C++
【C++】类和对象(四)上
1.初始化列表: 1.1为什么要有初始化列表? 实验代码如下:
45 0
|
11月前
|
存储 编译器 C语言
【C++】类和对象(上)
C++面向对象编程入门、类和对象的初步认识。
15413 6
|
10月前
|
编译器 C语言 C++
【类和对象(上)】(一)
【类和对象(上)】(一)
64 0
|
10月前
|
Java 编译器 C语言
类和对象(上)
类和对象(上)