【C++类和对象中:解锁面向对象编程的奇妙世界】(二)

简介: 【C++类和对象中:解锁面向对象编程的奇妙世界】

【C++类和对象中:解锁面向对象编程的奇妙世界】(一):https://developer.aliyun.com/article/1425447


那我们的栈类还能这样写吗?

Stack(Stack& stt)
{
  _array = stt._array; 
  _capacity = stt._capacity;
  _size = stt._size;
}


上面这种方法仍然是错误的,是浅拷贝,同样会调用两次析构函数。这里需要用到我们的深拷贝,思想是开辟一个资源一样大的空间,然后在把值拷贝过来。

#include <iostream>
using namespace std;
typedef int DataType;
class Stack
{
public:
  Stack(int capacity = 3)
  {
    _array = (DataType*)malloc(sizeof(DataType) * capacity);
    if (NULL == _array)
    {
      perror("malloc申请空间失败!!!");
      return;
    }
    _capacity = capacity;
    _size = 0;
  }
  //Stack(Stack& s)
  //{
  //  下面这种方法仍然是错误的,是浅拷贝
  //  _array = s._array; 
  //  _capacity = s._capacity;
  //  _size = s._size;
  //}
  Stack(Stack& stt)
  {
    _array = (int*)malloc(sizeof(int) * stt._capacity);
    if (_array == nullptr)
    {
      perror("malloc fail");
      exit(-1);
    }
    memcpy(_array, stt._array, sizeof(int) * stt._size);
    _size = stt._size;
    _capacity = stt._capacity;
  }
  void Print()
  {
    //...
  }
  ~Stack()
  {
    if (_array)
    {
      free(_array);
      _array = NULL;
      _capacity = 0;
      _size = 0;
    }
  }
private:
  DataType* _array;
  int _capacity;
  int _size;
};
void  func(Stack st)
{
  st.Print();
}
int main()
{
  Stack st1;
  func(st1);
  Stack st2(st1);//构造一个st2对象,用st1初始化
  func(st2);
  return 0;
}


通过监视窗口我们可以看到st1对象和st2对象指向的是不同的空间,但是内容都是一样的,此时调用的析构函数释放的空间就是不用的。


不知道我们有没有发现,上面的Date类就算没有拷贝构造函数,也是能正常运行的,这是因为拷贝构造函数时一个默认成员函数,对内置类型会完成值拷贝,而对自定义类型Stack需要调用它的拷贝构造函数,需要字节写拷贝函数。但是并不是所有的自定义类型都要写拷贝构造函数,比如下面的MyQueue类:

#include <iostream>
using namespace std;
typedef int DataType;
class Stack
{
public:
  Stack(int capacity = 3)
  {
    _array = (DataType*)malloc(sizeof(DataType) * capacity);
    if (NULL == _array)
    {
      perror("malloc申请空间失败!!!");
      return;
    }
    _capacity = capacity;
    _size = 0;
  }
  //Stack(Stack& s)
  //{
  //  下面这种方法仍然是错误的,是浅拷贝
  //  _array = s._array; 
  //  _capacity = s._capacity;
  //  _size = s._size;
  //}
  Stack(Stack& stt)
  {
    _array = (int*)malloc(sizeof(int) * stt._capacity);
    if (_array == nullptr)
    {
      perror("malloc fail");
      exit(-1);
    }
    memcpy(_array, stt._array, sizeof(int) * stt._size);
    _size = stt._size;
    _capacity = stt._capacity;
  }
  void Print()
  {
    //...
  }
  ~Stack()
  {
    if (_array)
    {
      free(_array);
      _array = NULL;
      _capacity = 0;
      _size = 0;
    }
  }
private:
  DataType* _array;
  int _capacity;
  int _size;
};
class MyQueue
{
  Stack _pushst;
  Stack _popst;
  int _size;
};
int main()
{
  MyQueue q1;
  MyQueue q2(q1);
  return 0;
}

运行结果:


这里也完成了我们的深拷贝。Date和MyQueue默认生成的拷贝构造函数就i可以使用,对应内置类型成员完成值拷贝,对应自定义类型成员调用这个成员的拷贝构造。但是Stack类需要字节写拷贝构造函数,完成深拷贝。像我们的顺序表、链表和二叉树都需要深拷贝。


3. 若未显式定义,编译器会生成默认的拷贝构造函数。 默认的拷贝构造函数对象按内存存储按 字节序完成拷贝,这种拷贝叫做浅拷贝,或者值拷贝。

#include <iostream>
using namespace std;
class Time
{
public:
  Time()
  {
    _hour = 1;
    _minute = 1;
    _second = 1;
  }
  //为防止写反,这里加const
  Time(const Time& t)
  {
    _hour = t._hour;
    _minute = t._minute;
    _second = t._second;
    cout << "Time::Time(const Time&)" << endl;
  }
private:
  int _hour;
  int _minute;
  int _second;
};
class Date
{
private:
  // 基本类型(内置类型)
  int _year = 1970;
  int _month = 1;
  int _day = 1;
  // 自定义类型
  Time _t;
};
int main()
{
  Date d1;
  // 用已经存在的d1拷贝构造d2,此处会调用Date类的拷贝构造函数
  // 但Date类并没有显式定义拷贝构造函数,则编译器会给Date类生成一个默认的拷贝构造函数
  Date d2(d1);
  return 0;
}

注意:在编译器生成的默认拷贝构造函数中,内置类型是按照字节方式直接拷贝的,而自定义类型是调用其拷贝构造函数完成拷贝的。


4. 编译器生成的默认拷贝构造函数已经可以完成字节序的值拷贝了,还需要自己显式实现吗? 当然像日期类这样的类是没必要的。那么下面的类呢?验证一下试试?

#include <iostream>
using namespace std;
// 这里会发现下面的程序会崩溃掉?这里就需要我们以后讲的深拷贝去解决。
typedef int DataType;
class Stack
{
public:
  Stack(size_t capacity = 10)
  {
    _array = (DataType*)malloc(capacity * sizeof(DataType));
    if (nullptr == _array)
    {
      perror("malloc申请空间失败");
      return;
    }
    _size = 0;
    _capacity = capacity;
  }
  void Push(const DataType& data)
  {
    // CheckCapacity();
    _array[_size] = data;
    _size++;
  }
  ~Stack()
  {
    if (_array)
    {
      free(_array);
      _array = nullptr;
      _capacity = 0;
      _size = 0;
    }
  }
private:
  DataType* _array;
  size_t _size;
  size_t _capacity;
};
int main()
{
  Stack s1;
  s1.Push(1);
  s1.Push(2);
  s1.Push(3);
  s1.Push(4);
  Stack s2(s1);
  return 0;
}


注意:类中如果没有涉及资源申请时,拷贝构造函数是否写都可以;一旦涉及到资源申请 时,则拷贝构造函数是一定要写的,否则就是浅拷贝。


5. 拷贝构造函数典型调用场景:

  • 使用已存在对象创建新对象
  • 函数参数类型为类类型对象
  • 函数返回值类型为类类型对象
#include <iostream>
using namespace std;
class Date
{
public:
  Date(int year, int minute, int day)
  {
    cout << "Date(int,int,int):" << this << endl;
  }
  Date(const Date& d)
  {
    cout << "Date(const Date& d):" << this << endl;
  }
  ~Date()
  {
    cout << "~Date():" << this << endl;
  }
private:
  int _year;
  int _month;
  int _day;
};
Date Test(Date d)
{
  Date temp(d);
  return temp;
}
int main()
{
  Date d1(2022, 1, 13);
  Test(d1);
  return 0;
}


为了提高程序效率,一般对象传参时,尽量使用引用类型,返回时根据实际场景,能用引用 尽量使用引用。


5.赋值运算符重载


5.1 运算符重载


class Date
{
public:
    Date(int year = 1900, int month = 1, int day = 1)
    {
        _year = year;
        _month = month;
        _day = day;
    }
private:
    int _year;
    int _month;
    int _day;
};
int main()
{
    Date d1;
    Date d2(2023, 10, 24);
    int x = 1, y = 2;
    bool ret1 = x > y;
    bool ret2 = x == y;
    //内置类型对象可以直接用各种运算符,内置类型都是简单类型
    //那自定义类型呢?
    //这里可以想象一下结构体的比较
    d1 == d2;//error
    d1 > d2;//error
    return 0;
}


运行结果:


这里需要想象一下结构体的比较,比较结构体是比较内部的成员,这里的类也是类似的。

#include <iostream>
using namespace std;
class Date
{
public:
    Date(int year = 1900, int month = 1, int day = 1)
    {
        _year = year;
        _month = month;
        _day = day;
    }
//private:
    int _year;
    int _month;
    int _day;
};
bool Geater(Date x1, Date x2)
{
    if (x1._year > x2._year)
        return true;
    else if (x1._year == x2._year && x1._month > x2._month)
        return true;
    else if (x1._year == x2._year && x1._month == x2._month && x1._day > x2._day)
        return true;
    else
        return false;
}
bool Equal(Date x1, Date x2)
{
    //成员私有不可访问
    //我们可以改一下上面的限制符private
    return x1._year == x2._year
        && x1._month == x2._month
        && x1._day == x2._day;
}
int main()
{
    Date d1;
    Date d2(2023, 10, 24);
    cout << Geater(d1, d2) << endl;
    cout << Equal(d1, d2) << endl;
    return 0;
}


运行结果:


C++为了增强代码的可读性引入了运算符重载,运算符重载是具有特殊函数名的函数,也具有其 返回值类型,函数名字以及参数列表,其返回值类型与参数列表与普通的函数类似。


函数名字为:关键字operator后面接需要重载的运算符符号。


函数原型:返回值类型 operator操作符(参数列表)


注意:

  • 不能通过连接其他符号来创建新的操作符:比如operator@
  • 重载操作符必须有一个类类型参数
  • 用于内置类型的运算符,其含义不能改变,例如:内置的整型+,不能通过重载运算法改变其内置类型的运算规则含义
  • 作为类成员函数重载时,其形参看起来比操作数数目少1,因为成员函数的第一个参数为隐藏的this
  • .*::(域作用限定符) sizeof?:(三目运算符). 注意以上5个运算符不能重载。这个经常在笔试选择题中出现。
#include <iostream>
using namespace std;
class Date
{
public:
    Date(int year = 1900, int month = 1, int day = 1)
    {
        _year = year;
        _month = month;
        _day = day;
    }
    //private:
    int _year;
    int _month;
    int _day;
};
//这里会调用拷贝构造,但其实没必要
//我们直接取别名即可
bool operator>(const Date& x1, const Date& x2)
{
    if (x1._year > x2._year)
        return true;
    else if (x1._year == x2._year && x1._month > x2._month)
        return true;
    else if (x1._year == x2._year && x1._month == x2._month && x1._day > x2._day)
        return true;
    else
        return false;
}
//这里会调用拷贝构造
bool operator==(const Date& x1, const Date& x2)
{
    return x1._year == x2._year
        && x1._month == x2._month
        && x1._day == x2._day;
}
int main()
{
    Date d1;
    Date d2(2023, 10, 24);
    cout << operator>(d1, d2) << endl;
    cout << operator==(d1, d2) << endl;
    //这里就可以直接写成内置类型比较的形式
    //由于流插入 << 优先级比 > 和 == 优先级高,所以这里需要加括号
    cout << (d1 > d2) << endl; //operator>(d1,d2)
    cout << (d1 == d2) << endl; //operator==(d1,d2)
    return 0;
}


这里需要分清运算符重载和函数重载之间的关系,它们之间没有任何关系

  • 运算符重载:自定义类型可以直接使用运算符
  • 函数重载:可以允许参数不同的同名函数


但是这里会发现运算符重载成全局的就需要成员变量是公有的,那么问题来了,封装性如何保证? 这里其实可以将函数移入到Date类中。


但是这里报错了为什么呢?编译器提示:error C2804: 二进制“operator >”的参数太多,因为类中含有一个隐藏的this参数

#include <iostream>
using namespace std;
class Date
{
public:
    Date(int year = 1900, int month = 1, int day = 1)
    {
        _year = year;
        _month = month;
        _day = day;
    }
    //这里隐藏了一个this参数
    // bool operator==(Date* this, const Date& d2)
    // 这里需要注意的是,左操作数是this,指向调用函数的对象
    bool operator>(const Date& x2)
    {
        if (_year > x2._year)
            return true;
        else if (_year == x2._year && _month > x2._month)
            return true;
        else if (_year == x2._year && _month == x2._month && _day > x2._day)
            return true;
        else
            return false;
    }
    //这里会调用拷贝构造
    bool operator==(const Date& x2)
    {
        return _year == x2._year
            && _month == x2._month                                
            && _day == x2._day;
    }
private:
    int _year;
    int _month;
    int _day;
};
int main()
{
    Date d1;
    Date d2(2023, 10, 24);
    cout << (d1 > d2) << endl; //d1.operator>(d2) ==> d1.operator>(&d1,d2)
    cout << (d1 == d2) << endl; //d1.operator==(d2) ==> d1.operator==(&d1,d2)
    return 0;
}


【C++类和对象中:解锁面向对象编程的奇妙世界】(三):https://developer.aliyun.com/article/1425465

相关文章
|
3月前
|
人工智能 机器人 编译器
c++模板初阶----函数模板与类模板
class 类模板名private://类内成员声明class Apublic:A(T val):a(val){}private:T a;return 0;运行结果:注意:类模板中的成员函数若是放在类外定义时,需要加模板参数列表。return 0;
84 0
|
3月前
|
存储 编译器 程序员
c++的类(附含explicit关键字,友元,内部类)
本文介绍了C++中类的核心概念与用法,涵盖封装、继承、多态三大特性。重点讲解了类的定义(`class`与`struct`)、访问限定符(`private`、`public`、`protected`)、类的作用域及成员函数的声明与定义分离。同时深入探讨了类的大小计算、`this`指针、默认成员函数(构造函数、析构函数、拷贝构造、赋值重载)以及运算符重载等内容。 文章还详细分析了`explicit`关键字的作用、静态成员(变量与函数)、友元(友元函数与友元类)的概念及其使用场景,并简要介绍了内部类的特性。
164 0
|
5月前
|
编译器 C++ 容器
【c++11】c++11新特性(上)(列表初始化、右值引用和移动语义、类的新默认成员函数、lambda表达式)
C++11为C++带来了革命性变化,引入了列表初始化、右值引用、移动语义、类的新默认成员函数和lambda表达式等特性。列表初始化统一了对象初始化方式,initializer_list简化了容器多元素初始化;右值引用和移动语义优化了资源管理,减少拷贝开销;类新增移动构造和移动赋值函数提升性能;lambda表达式提供匿名函数对象,增强代码简洁性和灵活性。这些特性共同推动了现代C++编程的发展,提升了开发效率与程序性能。
161 12
|
6月前
|
编译器 C++
类和对象(中 )C++
本文详细讲解了C++中的默认成员函数,包括构造函数、析构函数、拷贝构造函数、赋值运算符重载和取地址运算符重载等内容。重点分析了各函数的特点、使用场景及相互关系,如构造函数的主要任务是初始化对象,而非创建空间;析构函数用于清理资源;拷贝构造与赋值运算符的区别在于前者用于创建新对象,后者用于已存在的对象赋值。同时,文章还探讨了运算符重载的规则及其应用场景,并通过实例加深理解。最后强调,若类中存在资源管理,需显式定义拷贝构造和赋值运算符以避免浅拷贝问题。
|
6月前
|
存储 编译器 C++
类和对象(上)(C++)
本篇内容主要讲解了C++中类的相关知识,包括类的定义、实例化及this指针的作用。详细说明了类的定义格式、成员函数默认为inline、访问限定符(public、protected、private)的使用规则,以及class与struct的区别。同时分析了类实例化的概念,对象大小的计算规则和内存对齐原则。最后介绍了this指针的工作机制,解释了成员函数如何通过隐含的this指针区分不同对象的数据。这些知识点帮助我们更好地理解C++中类的封装性和对象的实现原理。
|
6月前
|
编译器 C++
类和对象(下)C++
本内容主要讲解C++中的初始化列表、类型转换、静态成员、友元、内部类、匿名对象及对象拷贝时的编译器优化。初始化列表用于成员变量定义初始化,尤其对引用、const及无默认构造函数的类类型变量至关重要。类型转换中,`explicit`可禁用隐式转换。静态成员属类而非对象,受访问限定符约束。内部类是独立类,可增强封装性。匿名对象生命周期短,常用于临时场景。编译器会优化对象拷贝以提高效率。最后,鼓励大家通过重复练习提升技能!
|
7月前
|
编译器 C++ 开发者
【C++篇】深度解析类与对象(下)
在上一篇博客中,我们学习了C++的基础类与对象概念,包括类的定义、对象的使用和构造函数的作用。在这一篇,我们将深入探讨C++类的一些重要特性,如构造函数的高级用法、类型转换、static成员、友元、内部类、匿名对象,以及对象拷贝优化等。这些内容可以帮助你更好地理解和应用面向对象编程的核心理念,提升代码的健壮性、灵活性和可维护性。
|
6月前
|
设计模式 安全 C++
【C++进阶】特殊类设计 && 单例模式
通过对特殊类设计和单例模式的深入探讨,我们可以更好地设计和实现复杂的C++程序。特殊类设计提高了代码的安全性和可维护性,而单例模式则确保类的唯一实例性和全局访问性。理解并掌握这些高级设计技巧,对于提升C++编程水平至关重要。
124 16
|
7月前
|
编译器 C语言 C++
类和对象的简述(c++篇)
类和对象的简述(c++篇)
|
6月前
|
安全 C++
【c++】继承(继承的定义格式、赋值兼容转换、多继承、派生类默认成员函数规则、继承与友元、继承与静态成员)
本文深入探讨了C++中的继承机制,作为面向对象编程(OOP)的核心特性之一。继承通过允许派生类扩展基类的属性和方法,极大促进了代码复用,增强了代码的可维护性和可扩展性。文章详细介绍了继承的基本概念、定义格式、继承方式(public、protected、private)、赋值兼容转换、作用域问题、默认成员函数规则、继承与友元、静态成员、多继承及菱形继承问题,并对比了继承与组合的优缺点。最后总结指出,虽然继承提高了代码灵活性和复用率,但也带来了耦合度高的问题,建议在“has-a”和“is-a”关系同时存在时优先使用组合。
324 6