2. C++的类和对象

简介: 2. C++的类和对象

C++类和对象初识

什么是类

C++类是对事物的一种抽象,万物都可以当做是类处理,类抽象的是什么?

  • 事物的特征:  数据成员表示 美女 : 年龄(int age) 体重(int weight)
  • 事物的行为:  成员函数表示 睡觉 购物....

什么是对象

对象可以说类的具体化(实例化)  美女(18,90kg)

类的创建

  • 掌握创建的语法
  • 掌握权限限定
  • 和结构体区别
  • 在没写构造函数之前,C语言结构体就按照C语言的方式用即可
  • 用了构造函数时候,大家把结构体直接当做C++类去使用
  • 结构体其实可以当做一个默认权限是公有属性的类
  • C++是允许空类和结构体存在
class 类名
{
  //默认为私有属性
  //.....
  public:     //类外只能访问公有属性
    //....公有属性
            //公有函数--->类外的公有接口
  protected:
    //....保护属性
  private:
    //....私有属性
};
//保护和私有属性区别,暂时不需要知道,后续讲继承的时候会讲
//类中没有权限可言

创建类完整代码

class MM 
{
public:
  void printData() 
  {
    cout << name << "\t" << age << "\t"<<num << endl;
  }
  void print();
protected:
private:    //一般数据成员写:私有属性
  string name;
  int age;
  int num;
};
//在类外实现类中的函数,必须要用类名限定(类名::函数名)
void MM::print() 
{
  cout << name << "\t" << age << "\t" << num << endl;
}

结构体和类的区别

#include <iostream>
using namespace std;
class MM 
{
  int num;      //类中默认的是私有属性
public:
  int age;
private:
  string name;
};
struct Boy
{           //结构体中默认的公有属性
  int num;
  int age;
private:
  string name;
};
//C语言是不能写空的结构体
//C++允许空结构体或者类
struct Empty 
{
  //占用内存不是0 是1(标记),写了数据这个标记就不存在
}m;
  //作用:泛型编程做参数包解析的递归循环终止处理
int main() 
{
  struct Boy boy;
  //boy.num = 1001;
  //boy.age = 12;
  MM mm;
  mm.age = 19;
  cout << sizeof(Empty) << endl;
  cout << sizeof(Boy) << endl;
  return 0;
}

对象创建和初始化

对象创建

  • 创建普通对象
  • 创建对象数组
  • 创建对象指针

对象的初始化

  • 类中直接给数据赋值
  • 提供一个共有接口去操作数据
  • 提供一个返回引用的接口

完整代码

#include <iostream>
#include <string>
using namespace std;
class MM 
{
public:
  void printData()    //普通成员函数只是写在类中,不占对象内存
  {
    cout << name << "\t" << age << "\t"<<num << endl;
  }
  void print();
  void initData(string mmName, int mmAge, int mmNum) 
  {
    name = mmName;
    age = mmAge;
    num = mmNum;
  }
  string& getName() { return name; }
  int& getAge() { return age; }
  int& getNum() { return num; }
protected:
private:    //一般数据成员写:私有属性
  string name="默认值";
  int age=0;
  int num=0;
};
//在类外实现类中的函数,必须要用类名限定(类名::函数名)
void MM::print() 
{
  cout << name << "\t" << age << "\t" << num << endl;
}
int main() 
{
  MM mm;      //创建对象
  MM array[3];
  MM* pMM;
  pMM = &mm;
  pMM = new MM;   //new一个对象
  //new一个对象过程
  //1.创建一个匿名对象(没有名字的对象)
  //2.把匿名对象的首地址赋值指针
  pMM->print();
  pMM->printData();
  //pMM->name = "小芳";   不可访问,类外不能访问public之外的所有属性
  cout << "通过提供共有接口传参的方式初始化对象的数据" << endl;
  mm.initData("小芳", 18, 1001);
  mm.printData();
  cout << "返回引用的去访问数据" << endl;
  MM* p = new MM;
  p->getName() = "MM";
  p->getAge() = 28;
  p->getNum() = 1004;
  p->printData();
  return 0;
}

成员的访问

  • 类中普通数据成员和成员函数必须通过对象去访问
  • 只有两种方案
  • 普通对象: 用 对象.成员访问
  • 对象指针:用 对象指针->成员

案例代码

#include <iostream>
#include <string>
#include <graphics.h>
#include <iomanip>
using namespace std;
class MM 
{
public:
  void initData(string mmName, int mmAge, int mmNum) 
  {
    name = mmName;
    age = mmAge;
    num = mmNum;
  }
  //不想让别人直接修改数据,不要返回引用,只能看不能操作
  string getName() { return name; }
  int getAge() { return age; }
  int getNum() { return num; }
private:
  string name;
  int age;
  int num;
};
void testObject() 
{
  MM mm;
  mm.initData("小芳", 19, 1002);
  cout << mm.getName() << "\t" << mm.getAge() << "\t" << mm.getNum() << endl;
  //IMAGE img;
  //img.getwidth();
  //img.getheight();
}
void testObjectPoint() 
{
  MM* pMM = new MM;
  pMM->initData("小丽", 29, 1004);
  cout << pMM->getName() << "\t" << pMM->getAge() << "\t" << pMM->getNum() << endl;
}
void testArray() 
{
  MM array[3];
  for (int i = 0; i < 3; i++) 
  {
    string name = "name" + to_string(i);
    array[i].initData(name,18+i,1002+i);
    cout << (array + i)->getName() << "\t" << (array + i)->getAge() << "\t" << (array + i)->getNum() << endl;
  }
}
int main() 
{
  //age = 123;   不能直接访问
  testObject();
  testObjectPoint();
  testArray();
  return 0;
}

类和对象的其他操作

类中含有指针问题

含有指针的处理方案和C语言的结构体中含有指针的处理方案是一样的,相对于C语言来说多了权限问题

#include <iostream>
#include <cstring>
using namespace std;
class MM
{
public:
  void initData(const char* mmName, int mmAge);
  void initMM(const char* mmName, int mmAge);
  void print()
  {
    cout << name << "\t" << age << endl;
  }
  char*& getName() 
  {
    return name;
  }
protected:
  char* name;
  int age;
};
//一般不采用这种方案处理,诟病很大
void MM::initData(const char* mmName, int mmAge)
{
  name = (char *)mmName;
  age = mmAge;
}
void MM::initMM(const char* mmName, int mmAge)
{
  name = new char[strlen(mmName) + 1];
  strcpy(name, mmName);
  age = mmAge;
}
void printConst(const char* str)  //传入常量和变量 传参const修饰
{
  cout << str << endl;
}
int main()
{
  MM* pMM = new MM;
  pMM->initData("张三", 19);
  pMM->print();
  //strcpy(pMM->getName(), "ILoveyou");  // 百分百有问题,name没有指向一段可操作内存
  char str[10] = "ILoveyou";
  //C++const要求更为严格,尤其是字符串处理
  printConst("ILoveyou");
  printConst(str);
  pMM->getName() =str;
  pMM->print();
  MM* p = new MM;
  p->initMM("ILoveyou",20);
  p->print();
  strcpy(p->getName(), "IMiss");
  p->print();
  return 0;
}

类不能直接包含自身的对象

只能包含自身指针不能包含自身对象

class Boy 
{
public:
  //Boy boy;       错误代码
  Boy* pBoy;    //指针正确
};

成员函数指针调用成员函数

class Test 
{
public:
  void print(string info) 
  {
    cout << info << endl;
  }
};
void testFunc() 
{
  Test test;
  //void (*Func)(string) = nullptr;
  //Func = &Test::print;     错误写法,类型
  //1.auto自动推断出类成员函数指针类型
  auto Funcf = &Test::print;   //没问题
  (test.*Funcf)("测试函数");   //调用还是要学会
  Test testb;
  (testb.*Funcf)("测试函数2");
  testb.print("直接调用");
  //2.正规写一下正常写法
  //不是简单的用*指针名替换函数,而是要加上类名限定
  void (Test:: *Func)(string) = nullptr;
  Func = &Test::print;      //类中所有东西,无论怎么访问,必须类名限定
  (test.*Func)("类成员函数指针访问成员函数");
}

对象本质

  • 对象的本质就是一个数据,只是数据包含操作
  • 因为对象的本质是一个数据,所以变量能做的,它都可以
  • 当做函数参数
  • 当做函数返回值
  • 当做另一个结构体数据成员
  • 当做另一个类的数据成员(类的组合,后面会讲)
class Student
{
public:
  void print() 
  {
    cout << name << "\t" << age << endl;
  }
  string& getName() 
  {
    return name;
  }
  int& getAge() 
  {
    return age;
  }
protected:
  string name;
  int age;
};
void printData(Student student) 
{
  student.print();
}
//子函数修改实参,C语言传入实参地址,C++传引用
void modifyStudent(Student& stu) 
{
  stu.getName() = "Memory";
  stu.getAge() = 28;
}
Student* createStu(string name, int age) 
{
  Student* p = new Student;
  p->getName() = name;
  p->getAge() = age;
  return p;
}
void testStudent() 
{
  Student stu;
  modifyStudent(stu);
  printData(stu);
  Student* p = createStu("C++", 19);
  p->print();
  Student temp = *p;
  temp.print();
  //除了赋值之外,其他运算不能直接做
  //Student temp1 = temp + temp;  //算术+条件
}
目录
相关文章
|
3天前
|
设计模式 安全 编译器
【C++11】特殊类设计
【C++11】特殊类设计
22 10
|
8天前
|
C++
C++友元函数和友元类的使用
C++中的友元(friend)是一种机制,允许类或函数访问其他类的私有成员,以实现数据共享或特殊功能。友元分为两类:类友元和函数友元。类友元允许一个类访问另一个类的私有数据,而函数友元是非成员函数,可以直接访问类的私有成员。虽然提供了便利,但友元破坏了封装性,应谨慎使用。
39 9
|
4天前
|
存储 编译器 C语言
【C++基础 】类和对象(上)
【C++基础 】类和对象(上)
|
12天前
|
编译器 C++
【C++】string类的使用④(字符串操作String operations )
这篇博客探讨了C++ STL中`std::string`的几个关键操作,如`c_str()`和`data()`,它们分别返回指向字符串的const char*指针,前者保证以&#39;\0&#39;结尾,后者不保证。`get_allocator()`返回内存分配器,通常不直接使用。`copy()`函数用于将字符串部分复制到字符数组,不添加&#39;\0&#39;。`find()`和`rfind()`用于向前和向后搜索子串或字符。`npos`是string类中的一个常量,表示找不到匹配项时的返回值。博客通过实例展示了这些函数的用法。
|
12天前
|
存储 C++
【C++】string类的使用③(非成员函数重载Non-member function overloads)
这篇文章探讨了C++中`std::string`的`replace`和`swap`函数以及非成员函数重载。`replace`提供了多种方式替换字符串中的部分内容,包括使用字符串、子串、字符、字符数组和填充字符。`swap`函数用于交换两个`string`对象的内容,成员函数版本效率更高。非成员函数重载包括`operator+`实现字符串连接,关系运算符(如`==`, `&lt;`等)用于比较字符串,以及`swap`非成员函数。此外,还介绍了`getline`函数,用于按指定分隔符从输入流中读取字符串。文章强调了非成员函数在特定情况下的作用,并给出了多个示例代码。
|
12天前
|
C++
【C++】string类的使用④(常量成员Member constants)
C++ `std::string` 的 `find_first_of`, `find_last_of`, `find_first_not_of`, `find_last_not_of` 函数分别用于从不同方向查找目标字符或子串。它们都返回匹配位置,未找到则返回 `npos`。`substr` 用于提取子字符串,`compare` 则提供更灵活的字符串比较。`npos` 是一个表示最大值的常量,用于标记未找到匹配的情况。示例代码展示了这些函数的实际应用,如替换元音、分割路径、查找非字母字符等。
|
12天前
|
C++
C++】string类的使用③(修改器Modifiers)
这篇博客探讨了C++ STL中`string`类的修改器和非成员函数重载。文章介绍了`operator+=`用于在字符串末尾追加内容,并展示了不同重载形式。`append`函数提供了更多追加选项,包括子串、字符数组、单个字符等。`push_back`和`pop_back`分别用于在末尾添加和移除一个字符。`assign`用于替换字符串内容,而`insert`允许在任意位置插入字符串或字符。最后,`erase`函数用于删除字符串中的部分内容。每个函数都配以代码示例和说明。
|
12天前
|
安全 编译器 C++
【C++】string类的使用②(元素获取Element access)
```markdown 探索C++ `string`方法:`clear()`保持容量不变使字符串变空;`empty()`检查长度是否为0;C++11的`shrink_to_fit()`尝试减少容量。`operator[]`和`at()`安全访问元素,越界时`at()`抛异常。`back()`和`front()`分别访问首尾元素。了解这些,轻松操作字符串!💡 ```
|
12天前
|
存储 编译器 Linux
【C++】string类的使用②(容量接口Capacity )
这篇博客探讨了C++ STL中string的容量接口和元素访问方法。`size()`和`length()`函数等价,返回字符串的长度;`capacity()`提供已分配的字节数,可能大于长度;`max_size()`给出理论最大长度;`reserve()`预分配空间,不改变内容;`resize()`改变字符串长度,可指定填充字符。这些接口用于优化内存管理和适应字符串操作需求。
|
17天前
|
C++
【C++】日期类Date(详解)②
- `-=`通过复用`+=`实现,`Date operator-(int day)`则通过创建副本并调用`-=`。 - 前置`++`和后置`++`同样使用重载,类似地,前置`--`和后置`--`也复用了`+=`和`-=1`。 - 比较运算符重载如`&gt;`, `==`, `&lt;`, `&lt;=`, `!=`,通常只需实现两个,其他可通过复合逻辑得出。 - `Date`减`Date`返回天数,通过迭代较小日期直到与较大日期相等,记录步数和符号。 ``` 这是236个字符的摘要,符合240字符以内的要求,涵盖了日期类中运算符重载的主要实现。