cpp篇~~类和对象

个人主页:strive_debug

1. 类的定义

1.1 类定义格式

class为定义类的关键字,Stack为类的名字,{}中为类的主体,注意类定义结束时后⾯ 分号不能省
略 。类体中内容称为类的成员:类中的变量称为成员变量(类的属性); 类中的函数称为成员函数(类的⽅法)。
为了区分成员变量,⼀般习惯上成员变量会加⼀个特殊标识加_ 开头。

复制代码
class Date
{
public:
  void Init(int year, int month, int day)
  {
    _year = year;
    _month = month;
    _day = day;
  }
private:
// 为了区分成员变量,⼀般习惯上成员变量
// 会加⼀个特殊标识,如 _ 开头
    int _year; 
    int _month;
    int _day;
};

C++兼容C中struct的⽤法,⼀般情况下我们还是推荐⽤class定义类。
唯一的区别:struct只能定义public函数。
定义在类⾯的成员函数默认为inline。

1.2 访问限定符

C++⼀种实现封装的⽅式,通过访问权限 选择性的将其接⼝提供给外部的⽤⼾使⽤。
public修饰的成员在类外可以直接被访问;protected和private修饰的成员在类外不能直接被访
问,protected和private是⼀样的。

class定义成员没有被访问限定符修饰时默认为private,struct默认为public。

⼀般成员变量都会被限制为private/protected,需要给别⼈使⽤的成员函数会放为public。

1.3 类域(namespace区分开来)

类定义了⼀个新的作⽤域,类的所有成员都在类的作⽤域中,在类体外定义成员时,需要使⽤ :: 作
⽤域操作符指明成员属于哪个类域。

复制代码
class Stack
{}:
void Stack::Init(int n)
{}

2. 实例化

类的实例化就像图纸一样,只设计没有制造,只是是声明没有分配空间。

复制代码
#include<iostream>
using namespace std;
class Date
{
public:
  void Init(int year, int month, int day)
  {
    _year = year;
    _month = month;
    _day = day;
}
   void Print()
  {
    cout << _year << "/" << _month << "/" << _day << endl;
  }
private:
// 这⾥只是声明,没有开空间
    int _year;
    int _month;
    int _day;
};

int main()
{
// Date类实例化出对象d1和d2
    Date d1;
    Date d2;
    d1.Init(2024, 3, 31);
    d1.Print();
    d2.Init(2024, 7, 5);
    d2.Print();
    return 0;
}

区分声明和定义(看是否分配/开辟空间)。

计算类对象的大小(只存储了成员变量,成员函数被放在了公共代码区)

遵循内存对齐的原则,VS的默认对齐数为8。

为什么要遵循(对齐的本质浪费了空间)

对齐数=编译器默认的一个对齐数与该成员大小的较小值。

结构体总大小:最大对齐数的整数倍。

注:没有成员变量的类,大小是1,不是0,开1bite位占位,不存储有效数据标识对象的存在。(如果不开空间怎么证明类对象存在过呢)

3. this指针(隐含的this)

编译器编译后,类的成员函数默认都会在形参第⼀个位置,增加⼀个当前类类型的指针,叫做this
指针。⽐如Date类的Init的真实原型为:

复制代码
void Init(Date* const this, int year, int month, int day)

类的成员函数中访问成员变量,本质都是通过this指针访问的(用于区分对象)

复制代码
class Date
{
public:
// void Init(Date* const this, int year, int month, int day)
void Init(int year, int month, int day)
{
// 编译报错:error C2106: "=": 左操作数必须为左值
// this = nullptr;
// this->_year = year;
    _year = year;
    this->_month = month;
    this->_day = day;
  }
  void Print()
  {
    cout << _year << "/" << _month << "/" << _day << endl;
  }
private:
// 这⾥只是声明,没有开空间
    int _year;
    int _month;
    int _day;
};

C++规定不能在实参和形参的位置显⽰的写this指针(编译时编译器会处理),但是可以在函数体内显
⽰使⽤this指针( 一句话就是不用管 )。

成员函数的指针是在编译时确定的,没有存在对象中,所以在指针为nullptr时不会报错,但是如果后面还有成员变量的存在就会报错,因为成员变量存储在对象中,指针为空指针的情况下,无法解引用。

4. 类的默认成员函数

面向类的三大特性:封装,继承,多态
类的默认成员函数(我们不写,编译器默认生成的函数,如果不满足需求需要自己写)

4.1 构造函数(完成初始化)

特殊的成员函数,虽然叫构造,但并不是开空间创建对象,而是对象实例化时初始化对象,本质是日代Stack和Date类中写的Init函数功能,自动调用的功能,完美替代了Init。(常使用的局部对象是栈帧创建时,空间就开好了)
特点:

  1. 函数名和类名相同

  2. 无返回值(返回值都不需要给,也不需要写void,规则如此)

  3. 对象实例化时系统自动调用对应的构建函数

  4. 构造函数可以重载

    复制代码
    Class Date//类和函数名相同
    {
    public:
    Date(int year = 1,int month = 1,int day = 1)//重载
        {
            ~~~~ //无返回值
        }
    private:
        int_year;
        int_month;
        int_day; 
    };
    
    int main()
    {
      Date d1;//自动调用
      Date d2(2026,1,1);
      return 0;
    }
  5. 如果类中没有显式定义构造函数,则C++编译器会⾃动⽣成⼀个⽆参的默认构造函数,⼀旦⽤⼾显式定义编译器将不再⽣成。

  6. ⽆参构造函数、全缺省构造函数、我们不写构造时编译器默认⽣成的构造函数,都叫做默认构造函数。但是这三个函数有且只有⼀个存在,不能同时存在。

  7. 我们不写,编译器默认⽣成的构造,对内置类型成员变量的初始化没有要求,也就是说是是否初始化是不确定的,看编译器。对于⾃定义类型成员变量,要求调⽤这个成员变量的默认构造函数初始化。如果这个成员变量,没有默认构造函数,那么就会报错,我们要初始化这个成员变量,需要⽤初始化列表才能解决,初始化列表。

说明:C++把类型分成内置类型(基本类型)和⾃定义类型。内置类型就是语⾔提供的原⽣数据类型,如:int/char/double/指针等,⾃定义类型就是我们使⽤class/struct等关键字⾃⼰定义的类型。
注:一般都自己写,编译器靠不住,东西也不多。

4.2 析构函数

析构函数与构造函数功能相反,不是完成对象本身的销毁,而是对资源的清理释放工作,类比Destroy功能,而Date严格说是不需要析构函数的。

特点:

  1. 析构函数名是在类名前加上字符 ~。
  2. ⽆参数⽆返回值。 (这⾥跟构造类似,也不需要加void)
  3. ⼀个类只能有⼀个析构函数。若未显式定义,系统会⾃动⽣成默认的析构函数。
  4. 对象⽣命周期结束时,系统会⾃动调⽤析构函数。
  5. 跟构造函数类似,我们不写编译器⾃动⽣成的析构函数对内置类型成员不做处理,⾃定类型成员会调⽤他的析构函数。
  6. 还需要注意的是我们显⽰写析构函数,对于⾃定义类型成员也会调⽤他的析构,也就是说⾃定义类型成员⽆论什么情况都会⾃动调⽤析构函数。
  7. 如果类中没有申请资源时,析构函数可以不写,直接使⽤编译器⽣成的默认析构函数,如Date;如果默认⽣成的析构就可以⽤,也就不需要显⽰写析构,如MyQueue;但是有资源申请时,⼀定要⾃⼰写析构,否则会造成资源泄漏,如Stack。
  8. ⼀个局部域的多个对象,C++规定后定义的先析构。

4.3 拷⻉构造函数

如果⼀个构造函数的第⼀个参数是⾃⾝类类型的引⽤,且任何额外的参数都有默认值,则此构造函数也叫做拷⻉构造函数,也就是说拷⻉构造是⼀个特殊的构造函数。如:

复制代码
Date(const Date &d)
{
  _year=d._year;
  _month=d._month;
  _day=d._day;
}

int main()
{
  Date d1;
  //Date d4 = d1;拷贝构造两种写法
  Date d4(d1);
}

*c++规定类类型传值传参必须调用拷贝构造(除非引用),拷贝构造没用引用,会形成无穷递归。
拷⻉构造的特点:

  1. 拷⻉构造函数是构造函数的⼀个重载。
  2. 拷⻉构造函数的第⼀个参数必须是类类型对象的引⽤,使⽤传值⽅式编译器直接报错,因为语法逻辑上会引发⽆穷递归调⽤。 拷⻉构造函数也可以多个参数,但是第⼀个参数必须是类类型对象的引⽤,后⾯的参数必须有缺省值。
  3. C++规定⾃定义类型对象进⾏拷⻉⾏为必须调⽤拷⻉构造,所以这⾥⾃定义类型传值传参和传值返回都会调⽤拷⻉构造完成。
  4. 若未显式定义拷⻉构造,编译器会⽣成⾃动⽣成拷⻉构造函数。⾃动⽣成的拷⻉构造对内置类型成员变量会完成值拷⻉/浅拷⻉(⼀个字节⼀个字节的拷⻉),对⾃定义类型成员变量会调⽤他的拷⻉构造。
  5. Date内置类型不需要显⽰实现拷⻉构造。像Stack这样的类,虽然也都是内置类型,但是_a指向了资源,编译器⾃动⽣成的拷⻉构造不符合我们的需求,需要⾃⼰实现深拷⻉(对指向的资源也进⾏拷⻉)。MyQueue⾃定义类型,不显⽰实现。技巧:如果⼀个类显⽰实现了析构并释放资源,那么他就需要显⽰写拷⻉构造,否则就不需要。
  6. 传值返回会产⽣⼀个临时对象调⽤拷⻉构造,传值引⽤返回,返回的是返回对象的别名(如:*this。this是地址,*this是对象返回的一般都是对象,而判断一般都是地址),没有产⽣拷⻉。但是如果返回对象是⼀个当前函数局部域的局部对象,函数结束就销毁了,那么使⽤引⽤返回是有问题的,这时的引⽤相当于⼀个野引⽤,类似⼀个野指针⼀样。传引⽤返回可以减少拷⻉,但是⼀定要确保返回对象,在当前函数结束后还在,才能⽤引⽤返回。

如果传引用返回,不加static修饰的话,Func()结束就销毁,ret接受的就是一个野引用。加了static之后,先拷贝了在销毁调用两次析构。

5. 赋值运算符重载

5.1 运算符重载(operator和后面定义的运算符)

运算符重载特性:

  1. 类类型对象使⽤运算符时,必须转换成调⽤对应运算符重载,若没有对应的运算符重载,则会编译报错。

  2. 运算符重载是具有特殊名字的函数,他的名字是由operator和后⾯要定义的运算符共同构成。和其他函数⼀样,它也具有其返回类型和参数列表以及函数体。

  3. 重载运算符函数的参数个数和该运算符作⽤的运算对象数量⼀样多。⼀元运算符有⼀个参数(*/++/--),⼆元运算符有两个参数(+/-),⼆元运算符的左侧运算对象传给第⼀个参数,右侧运算对象传给第⼆个参数。

  4. *如果⼀个重载运算符函数是成员函数,则它的第⼀个运算对象默认传给隐式的this指针,因此运算符重载作为成员函数时,参数⽐运算对象少⼀个。

  5. 运算符重载以后,其优先级和结合性与对应的内置类型运算符保持⼀致。

  6. 不能通过连接语法中没有的符号来创建新的操作符:⽐如operator@。

  7. " . * " " :: " " sizeof " " ? : " " . " 注意以上5个运算符不能重载。(选择题⾥⾯常考)。.*用于调用成员函数的指针(一般函数指针都typedef)。

  8. ⼀个类需要重载哪些运算符,是看哪些运算符重载后有意义,⽐如Date类重载operator-就有意义,但是重载operator+就没有意义。
    9. 重载操作符⾄少有⼀个类类型参数,不能通过运算符重载改变内置类型对象的含义,如: int
    operator+(int x, int y)

  9. 重载++运算符时,有前置++和后置++,运算符重载函数名都是operator++,⽆法很好的区分。C++规定,后置++重载时,增加⼀个int形参,跟前置++构成函数重载,⽅便区分。
    把私有放成公有(存在风险):

    #include<iostream>
    using namespace std;
    class Date
    {
    public:
    Date(int year = 1, int month = 1, int day = 1)
    {
    _year = year;
    _month = month;
    _day = day;
    }
    void Print()
    {
    cout << _year << "-" << _month << "-" << _day << endl;
    }
    //private:把私有放成公有
    int _year;
    int _month;
    int _day;
    };
    bool operator==(const Date& d1, const Date& d2)
    {
    return d1._year == d2._year
    && d1._month == d2._month
    && d1._day == d2._day;
    }
    int main()
    {
    Date d1(2024, 7, 5);
    Date d2(2024, 7, 6);
    // 运算符重载函数可以显⽰调⽤
    operator==(d1, d2);
    // 编译器会转换成 operator==(d1, d2);
    d1 == d2;
    return 0;
    }

注:存在成员变量私有无法访问的问题。
方法:

  1. 提供对应的get xxx函数
  2. 友元(不推荐)
  3. 重载为成员函数

重载为成员函数:

复制代码
#include<iostream>
using namespace std;
class Date
{
public:
  Date(int year = 1, int month = 1, int day = 1)
  {
    _year = year;
    _month = month;
    _day = day;
  }
  void Print()
  {
    cout << _year << "-" << _month << "-" << _day << endl;
  }
  bool operator==(const Date& d)
  {
    return _year == d._year
    && _month == d._month
    && _day == d._day;
  }
private:
  int _year;
  int _month;
  int _day;
};

int main()
{
  Date d1(2024, 7, 5);
  Date d2(2024, 7, 6);
  // 运算符重载函数可以显⽰调⽤
  d1.operator==(d2);
  // 编译器会转换成 d1.operator==(d2);
  d1 == d2;
return 0;
}

前置++和后置++的写法:

复制代码
//++d1;返回+之后的
Date& operator++()
{
*this+=1;
return *this;
}

//d1++;返回+之前的
Date operator++(int)
{
Date tmp;
*this+=1;
return tmp;
}

5.2 赋值运算符重载

用于两个已存在的对象(初始化完的)直接的拷贝赋值,与拷贝构造做区分,拷贝构造适用于一个已存在的对象,初始化给另一个要创建的对象。

复制代码
Date d1 (2026,1,1);

//构造
Date d2 (d1);
Date d4 = d1;

//赋值重载
Date d3 (2026,2,1);
d1 = d2;

特性:

  1. 赋值运算符重载是⼀个运算符重载,规定必须重载为成员函数。赋值运算重载的参数建议写成
    const 当前类类型引⽤,否则会传值传参会有拷⻉。

  2. 有返回值,且建议写成当前类类型引⽤,引⽤返回可以提⾼效率,有返回值⽬的是为了⽀持连续赋值场景。
    3其余的和构造函数等一样,stack需要自己实现,内置类型(Date),MyQueue自动生成的就够用。
    注:为了防止有人自己对自己赋值重载,一般会判断一下。

    Date& operator=(const Date& d)
    {
    // 不要检查⾃⼰给⾃⼰赋值的情况
    if (this != &d)
    {
    _year = d._year;
    _month = d._month;
    _day = d._day;
    }
    // d1 = d2表达式的返回对象应该为d1,也就是*this this是地址
    return *this;
    }

总结:

  1. 构造一般都需要自己写,自己传参定义初始化。
  2. 虚构、构造时有资源申请(如malloc或fopen)等,就需要显示写。
  3. 拷贝构造和赋值重载,显示写了析构,内部管理资源就需要显示是实现深拷贝。

5.3 ⽇期类实现

时间类的实现需要注意+,+=,实现+只需要拷贝一下,在进行+=

复制代码
#include<iostream>
#include<assert.h>
using namespace std;
class Date
{
	// 友元函数声明
	friend ostream& operator<<(ostream& out, const Date& d);
	friend istream& operator>>(istream& in, Date& d);

public:
	Date(int year = 1, int month = 1, int day = 1);
	void Print();

	bool operator<(const Date& d);
	bool operator>(const Date& d);
	bool operator<=(const Date& d);
	bool operator>=(const Date& d);
	bool operator==(const Date& d);
	bool operator!=(const Date& d);

	int GetMonthDay(int year, int month)
	{
		assert(month > 0 && month < 13);
		//getmonthday会被高频的调用,加static,让getmonthday变成静态,让其放在静态区
		static int monthDayArray[13] = { -1, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
		// 365天 5h +
		if (month == 2 && ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)))
		{
			return 29;
		}
		else
		{
			return monthDayArray[month];
		}
	}

	bool CheckDate();

	Date& operator+=(int day);
	Date operator+(int day);

	Date& operator-=(int day);
	Date operator-(int day);

	Date& operator++();
	Date operator++(int);

	Date& operator--();
	Date operator--(int);

	int operator-(const Date& d); 
private:
	int _year;
	int _month;
	int _day;
};


// 重载
ostream& operator<<(ostream& out, const Date& d);
istream& operator>>(istream& in, Date& d);


#include"Date.h"

Date::Date(int year, int month, int day)
{
	_year = year;
	_month = month;
	_day = day;
}
void Date::Print()
{
	cout << _year << "-" << _month << "-" << _day << endl;
}

bool Date::operator<(const Date& d)
{
	if (_year < d._year)
	{
		return true;
	}
	else if (_year == d._year
		&& _month < d._month)
	{
		return true;
	}
	else if (_year == d._year
		&& _month == d._month
		&& _day < d._day)
	{
		return true;
	}

	return false;
}
bool Date::operator>(const Date& d)
{
	//基础的写法
	/*if (_year > d._year)
	{
		return true;
	}
	else if (_year == d._year
		&& _month > d._month)
	{
		return true;
	}
	else if (_year == d._year
		&& _month == d._month
		&& _day > d._day)
	{
		return true;
	}
	return false;*/

	//更简单的写法,直接利用其特性运算符重载
	//return !(*this < d || *this == d);
	return !(*this <= d);
}
bool Date::operator<=(const Date& d)
{
	//基础的写法
		//if (*this == d)
		//{
		//	return true;
		//}
		//else if (_year < d._year)
		//{
		//	return true;
		//}
		//else if (_year == d._year
		//	&& _month > d._month)
		//{
		//	return true;
		//}
		//else if (_year == d._year
		//	&& _month == d._month
		//	&& _day > d._day)
		//{
		//	return true;
		//}

	//更简单的写法,直接利用其特性运算符重载
	return *this < d || *this == d;
}
bool Date::operator>=(const Date& d)
{
	return *this > d || *this == d;
}
bool Date::operator==(const Date& d)
{
	return _year == d._year
		&& _month == d._month
		&& _day == d._day;
}
bool Date::operator!=(const Date& d)
{
	return!(*this == d);
}
//实践当中先写+=效率更高些,+会有拷贝操作tmp,如果先实现+,就会出现大量拷贝
Date& Date::operator+=(int day)
{
	if (day < 0)
	{
		return *this -= -day;
	}
	_day += day;
	while (_day > GetMonthDay(_year, _month))
	{
		_day -= GetMonthDay(_year, _month);
		++_month;
		if (_month == 13)
		{
			_year++;
			_month = 1;
		}
	}
	//如果先写出了+,也可以通过重载加赋值的方法写
	//*this = *this + day;
	return *this;
}
//注意:想要用运算符重载的前提是要写出对应的运算符函数,不能上来就套娃

Date Date::operator+(int day)
{
	Date tmp = *this;
	//tmp._day += day;
	//while (tmp._day > GetMonthDay(tmp._year, tmp._month))
	//{
	//	tmp._day -= GetMonthDay(tmp._year, tmp._month);
	//	++tmp._month;
	//	if (tmp._month == 13)
	//	{
	//		tmp._year++;
	//		tmp._month = 1;
	//	}
	//}
	//先写出+=时可以直接重载用
	tmp += day;
	return tmp;
}

Date& Date::operator-=(int day)
{
	if (day < 0)
	{
		return *this += -day;
	}
	_day -= day;
	while (_day <= 0)
	{
		--_month;
		if (_month == 0)
		{
			--_year;
			_month == 12;
		}
		_day += GetMonthDay(_year, _month);
	}
	return *this;
}
Date Date::operator-(int day)
{
	Date tmp = *this;//Date tmp (*this);
	tmp -= day;

	return tmp;
}

//前置++d1
Date& Date::operator++()
{
	*this += 1;
	return *this;
}
//后置d1++
Date Date::operator++(int)
{
	Date tmp = *this;
	*this += 1;
	return tmp;
}

//前置--d1
Date& Date::operator--()
{
	*this -= 1;
	return *this;
}
//后置d1--
Date Date::operator--(int)
{
	Date tmp = *this;
	*this -= 1;
	return tmp;
}

//d1-d2
int Date::operator-(const Date& d)
{
	Date max = *this;
	Date min = d;
	int flog = 1;
	if (*this < d)
	{
		max = d;
		min = *this;
		int flog = -1;
	}

	int n = 0;
	while (min != max)
	{
		++min;
		++n;
	}

	return n * flog;

}

bool Date::CheckDate()
{
	if (_month < 1 || _month > 12
		|| _day < 1 || _day > GetMonthDay(_year, _month))
	{
		return false;
	}
	else
	{
		return true;
	}
}
ostream& operator<<(ostream& out, const Date& d)
{
	cout << d._year << "年" << d._month << "月" << d._day << "日" << endl;
	return out;
}
istream& operator>>(istream& in, Date& d)
{
	cout << "请输入年月日:>";
	in >> d._year >> d._month >> d._day;
	if (!d.CheckDate())
	{
		cout << "日期非法" << endl;
	}
	return in;
}

#include"Date.h"
//int main()
//{
//	Date d1(2025, 2, 1);
//	Date d2;
//	d1.Print();
//
//	//加减测试
//	//d1 += 100;
//	//d1.Print();
//	//d2 = d1 + 100;
//	//d2 = d1 - 100;
//
//	//结果测试
//	//++d1;
//	//d1.Print();
//	//d1++;
//	//d1.Print();
//	//--d1;
//	//d1.Print();
//	//d1--;
//	//d1.Print();
//
//	//对返回值的测试
//	//Date ret1=d1++;
//	//ret1.Print();
//	//Date ret2=++d1;
//	//ret2.Print();
//	//Date ret2 = --d1;
//	//ret2.Print();
//	//Date ret1=d1--;
//	//ret1.Print();
//
//	return 0;
//}

int main()
{
	//Date d1(2025, 12, 1);
	//Date d2(2026, 1, 2);

	//cout << d1 - d2 << endl;
	//cout << d2 - d1 << endl;

	//cout << d1;
	//cout << d1 << d2 << endl;
	Date d1;
	Date d2;
	cin >> d1 >> d2;
	cout << d1 << d2 << endl;
	return 0;
}

6.取地址运算符重载

6.1const成员函数*

  • 将const修饰的成员函数称之为const成员,const修饰成员函数放到成员功函数参数列表的后面。
  • cosnt实际修饰该成员函数隐含的this指针,表明在该成员函数中不能对类的任何成员进行修改。const修饰Date类的printf成员函数,Print隐含的this指针由Date* cosnt this变成const Date* cosnt this。

原则:应加尽加
总结:一个成员函数在不修改成员变量的前提上建议加上cosnt。

6.2 取地址运算符重载

一般不用写,编译器自动生成的就够用,一些极特殊的情况(不想让人获得 当前类对象的地址) 就可以⾃⼰实现⼀份,胡乱返回⼀个地址。

复制代码
Date* operator &()
{  
  return nullptr;       //使坏版:return (const Date*) 0x12345fff;
}

cosnt Date* operator &() const
{

  return nullptr;
}

7. 初始化列表

特性:

  1. 引用成员变量,cosnt成员变量,没有默认构造的类类型变量,必须放在初始化列表的位置进行初始化,否则编译报错。

  2. c++11支持在成员变量声明的位置给缺省值,这个缺省值主要是给没有显示在初始化列表的成员使用的。

  3. *初始化列表按照成员的声明顺序进行初始化,跟成员在初始化列表出现的先后顺序无关,建议声明顺序和初始化列表顺序保持一致。

    public:
    Date(int& x, int year = 1, int month = 1, int day = 1)
    :_year(year)
    ,_month(month)
    ,_day(day)
    {

    }

    private:
    // 注意这⾥不是初始化,这⾥给的是缺省值,这个缺省值是给初始化列表的
    // 如果初始化列表没有显⽰初始化,默认就会⽤这个缺省值初始化
    int _year = 1;
    int _month = 1;
    int _day;

8. 类型转换

需要借助内置类型为参数的构造函数
特性:

  1. C++⽀持内置类型隐式类型转换为类类型对象,需要有相关内置类型为参数的构造函数。

  2. 构造函数前⾯加explicit就不再⽀持隐式类型转换。

  3. 类类型的对象之间也可以隐式转换,需要相应的构造函数支持

    #include<iostream>
    using namespace std;
    class A
    {
    public:

    // 构造函数explicit就不再⽀持隐式类型转换
    // explicit A(int a1)
    A(int a1)
    :_a1(a1)
    {}

    //explicit A(int a1, int a2)
    A(int a1, int a2)
    :_a1(a1)
    , _a2(a2)
    {}

    void Print()
    {
    cout << _a1 << " " << _a2 << endl;
    }

    int Get() const
    {
    return _a1 + _a2;
    }

    private:

    int _a1 = 1;
    int _a2 = 2;
    };

    class B
    {
    public:

    B(const A& a)
    :_b(a.Get())
    {}

    private:

    int _b = 0;
    };

    int main()
    {
    // 1构造⼀个A的临时对象,再⽤这个临时对象拷⻉构造aa3
    // 编译器遇到连续构造+拷⻉构造->优化为直接构造
    A aa1 = 1;
    aa1.Print();
    const A& aa2 = 1;
    // C++11之后才⽀持多参数转化
    A aa3 = { 2,2 };
    // aa3隐式类型转换为b对象
    // 原理跟上⾯类似
    B b = aa3;
    const B& rb = aa3;
    return 0;
    }

9. static成员

特性:

  1. ⽤static修饰的成员变量,称之为静态成员变量,静态成员变量⼀定要在类外进⾏初始化。

  2. 静态成员变量为所有类对象所共享,不属于某个具体的对象,不存在对象中,存放在静态区。

  3. ⽤static修饰的成员函数,称之为静态成员函数,静态成员函数没有this指针。

  4. 静态成员函数中可以访问其他的静态成员,但是不能访问⾮静态的,因为没有this指针。

  5. ⾮静态的成员函数,可以访问任意的静态成员变量和静态成员函数。

  6. 突破类域就可以访问静态成员,可以通过类名::静态成员 或者 对象.静态成员 来访问静态成员变量 和静态成员函数。

  7. 静态成员也是类的成员,受public、protected、private 访问限定符的限制。

  8. 静态成员变量不能在声明位置给缺省值初始化,因为缺省值是个构造函数初始化列表的,静态成员 变量不属于某个对象,不⾛构造函数初始化列表。

    {
    private:

    static int_scount; //√
    static int_scount =1; //×
    };

    int A:: _scount =0; //√

10. 友元

特性:

  1. 友元提供了⼀种突破类访问限定符封装的⽅式,友元分为:友元函数和友元类,在函数声明或者类声明的前⾯加friend,并且把友元声明放到⼀个类的⾥⾯。

  2. 外部友元函数可访问类的私有和保护成员,友元函数仅仅是⼀种声明,他不是类的成员函数。

  3. 友元函数可以在类定义的任何地⽅声明,不受类访问限定符限制。

  4. ⼀个函数可以是多个类的友元函数。

  5. 友元类中的成员函数都可以是另⼀个类的友元函数,都可以访问另⼀个类中的私有和保护成员。

  6. 友元类的关系是单向的,不具有交换性,⽐如A类是B类的友元,但是B类不是A类的友元。

  7. 友元类关系不能传递,如果A是B的友元, B是C的友元,但是A不是C的友元。

  8. 有时提供了便利。但是友元会增加耦合度,破坏了封装,所以友元不宜多⽤。

    #include<iostream>
    using namespace std;
    class A
    {
    // 友元声明
    friend class B;
    private:

    int _a1 = 1;
    int _a2 = 2;
    };

    class B
    {
    public:

    void func1(const A& aa)
    {
    cout << aa._a1 << endl;
    cout << _b1 << endl;
    }

    void func2(const A& aa)
    {
    cout << aa._a2 << endl;
    cout << _b2 << endl;
    }
    private:

    int _b1 = 3;
    int _b2 = 4;
    };

    int main()
    {
    A aa;
    B bb;
    bb.func1(aa);
    bb.func1(aa);
    return 0;
    }

11. 内部类

  1. 是⼀个独⽴的类,跟定义在 全局相⽐,他只是受外部类类域限制和访问限定符限制,所以外部类定义的对象中不包含内部类。

  2. 内部类默认是外部类的友元类。

  3. 内部类本质也是⼀种封装,当A类跟B类紧密关联,A类实现出来主要就是给B类使⽤,那么可以考虑把A类设计为B的内部类,如果放到private/protected位置,那么A类就是B类的专属内部类,其他地⽅都⽤不了。

    #include<iostream>
    using namespace std;

    class A
    {
    private:

    static int _k;
    int _h = 1;
    public:

    class B // B默认就是A的友元
    {
    public:

    复制代码
        void foo(const A& a)
        {
           cout << _k << endl; //OK
           cout << a._h << endl; //OK
        }
             int _b1;
    };

    };
    int A::_k = 1;

    int main()
    {
    cout << sizeof(A) << endl;
    A::B b;
    A aa;
    b.foo(aa);
    return 0;
    }

12. 匿名对象(类似于临时对象)

匿名对象,生命周期当前一行,构造完就析构。

引用时要加const,并且会延长生命周期,跟着引用走,引用结束了,匿名对象的声明周期也跟着结束。

复制代码
//没有具体的名字
//比如就叫A
A aa1(1); A aa2; A(1); A();  //有名无参可不加(),无名不行

编译器对构造的优化 (构造+拷贝构造-->构造)

vs2019 拷贝构造+拷贝构造 --> 合二为一

vs2022 拷贝构造+拷贝构造 --> 一个构造

相关推荐
打工的小王2 小时前
单例模式的实现
java·开发语言·单例模式
是宇写的啊2 小时前
单例模式-阻塞队列
java·开发语言·单例模式
进击的小头2 小时前
Git在C项目中的分支策略和规范
c语言·开发语言·git
u0104058362 小时前
Java中的单例模式详解
java·开发语言·单例模式
Allen_LVyingbo2 小时前
构建医疗AI数据集建设平台:Go语言工程方案详解
开发语言·人工智能·自然语言处理·golang·知识图谱·健康医疗
历程里程碑2 小时前
哈希1:两数之和:哈希表优化指南
java·开发语言·数据结构·c++·算法·哈希算法·散列表
XerCis2 小时前
Python包与环境管理工具uv及pyproject.toml指南
开发语言·python·uv
oioihoii2 小时前
Vibe Coding在QT桌面开发中的可行性分析
开发语言·人工智能·qt
码界奇点2 小时前
Tomcat与JDK版本对照全解析避坑指南生产环境选型建议
java·开发语言·容器·jdk·tomcat