当前位置: 首页 > news >正文

第四讲:类与对象(下)

目录

1、再谈构造函数

1.1、构造函数体赋值

1.2、初始化列表

 1.3、explicit关键字

2、static成员

3、友元

3.1、友元函数

3.2、友元类

4、内部类

5、匿名对象

6、拷贝对象时的优化(了解)

7、重新理解类与对象

8、日期类的实现

9、练习题

9.1、第一题

9.2、第二题

9.3、第三题

9.4、第四题

9.5、第五题


1、再谈构造函数

1.1、构造函数体赋值

在创建对象时,编译器通过调用构造函数,给对象中各个成员变量一个合适的初始值。

例如:

class Date
{
public:
	Date(int year, int month, int day)
	{
		_year = year;
		_month = month;
		_day = day;
	}
private:
	int _year;
	int _month;
	int _day;
};

虽然上述构造函数调用之后,对象中已经有了一个初始值,但是不能将其称为对对象中成员变量 的初始化,构造函数体中的语句只能将其称为赋初值,而不能称作初始化。因为初始化只能初始 化一次,而构造函数体内可以多次赋值。

1.2、初始化列表

初始化列表:以一个冒号开始,接着是一个以逗号分隔的数据成员列表,每个"成员变量"后面跟一个放在括号中的初始值或表达式。构造函数都是有初始化列表的,都是可以使用初始化列表的。

例如:

class Date
{
public:
    Date(int year, int month, int day)
        :_year(year)
        ,_month(month)
        ,_day(day)
    {}
private:
    int _year;
    int _month;
    int _day;
};

1、每个成员变量在初始化列表中只能出现一次(初始化只能初始化一次)。

2、类中包含以下成员,必须放在初始化列表位置进行初始化:引用成员变量(因为引用也必须在定义的时候进行初始化),const成员变量(因为const修饰的变量必须在定义时初始化),自定义类型成员(且该类没有默认构造函数时)。

例如:

class A
{
public:
	A(int a)
		:_a(a)
	{}

private:
	int _a;
};

class B
{
public:
	B(int a, int ref)
		:_aobj(a)
		, _ref(ref)
		, _n(10)
	{}

private:
	A _aobj;  // 没有默认构造函数
	int& _ref;  // 引用
	const int _n; // const 
};

3、尽量使用初始化列表初始化,因为不管你是否使用初始化列表,对于自定义类型成员变量, 一定会先使用初始化列表初始化。

注:尽量使用初始化列表进行初始化,因为不论如何都要走初始化列表,因为初始化列表是成员变量定义的地方。(不写初始化列表,初始化列表仍然存在)。当然不是所有的情况都能用初始化列表来进行初始化,只是对于能用初始化列表来初始化的就尽量用初始化列表来进行初始化。

例如:

class Time
{
public:
	Time(int hour = 0)
		:_hour(hour)
	{
		cout << "Time()" << endl;
	}

private:
	int _hour;
};

class Date
{
public:
	Date(int day)
	{}

private:
	int _day;
	Time _t;
};

int main()
{
	Date d(1);
	return 0;
}

4、成员变量在类中声明次序就是其在初始化列表中的初始化顺序,与其在初始化列表中的先后次序无关

例如:

class A
{
public:
    A(int a)
        :_a1(a)
        ,_a2(_a1)
    {}

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

private:
    int _a2;
    int _a1;
};

int main()
{
    A aa(1);
    aa.Print();
    return 0;
}

运行结果为:

 1.3、explicit关键字

构造函数不仅可以构造与初始化对象,对于单个参数或者除第一个参数无默认值其余均有默认值 的构造函数,还具有类型转换的作用。

例如:

class Date
{
public:
	//1. 单参构造函数,没有使用explicit修饰,具有类型转换作用
	//explicit修饰构造函数,禁止类型转换
	explicit Date(int year)
		:_year(year)
	{}

	/*
	 //2. 虽然有多个参数,但是创建对象时后两个参数可以不传递,没有使用explicit修饰,具有类型转换作用
     //explicit修饰构造函数,禁止类型转换
    explicit Date(int year, int month = 1, int day = 1)
		: _year(year)
		, _month(month)
		, _day(day)
	{}
	*/

	Date& operator=(const Date& d)
	{
		if (this != &d)
		{
			_year = d._year;
			_month = d._month;
			_day = d._day;
		}
		return *this;
	}

private:
	int _year;
	int _month;
	int _day;
};

int main()
{
	Date d1(2022);
	// 用一个整形变量给日期类型对象赋值,实际编译器背后会用2023构造一个无名对象,最后用无名对象给d1对象进行赋值
	d1 = 2023;
	// 将1屏蔽掉,2放开时则编译失败,因为explicit修饰构造函数,禁止了单参构造函数类型转换的作用
	return 0;
}

如图:

用explicit修饰构造函数,将会禁止构造函数的隐式转换。上图中的两个临时变量都具有常性,即不变。

当自定义类型发生隐式类型转换时,C++对于自定义这种产生中间临时变量会进行优化,例如:构造+拷贝构造进行优化就变成了构造。也就是说,上图A aa1=1;这个隐式类型的转换,实际上会变成直接构造,省去了拷贝构造。

注:并不是所有的编译器都会进行优化,但是一般新的编译器都会优化。(关于拷贝对象时编译器的优化,具体将在下文展开。)

C++11中还出现了多参数构造函数也支持隐式类型转换,例如:

class Date
{
public:
	explicit Date(int year,int month,int _day=0)//若不使用explicit修饰则不会报错
		:_year(year)
		,_month(month)
	{}

	
	Date& operator=(const Date& d)
	{
		if (this != &d)
		{
			_year = d._year;
			_month = d._month;
			_day = d._day;
		}
		return *this;
	}

private:
	int _year;
	int _month;
	int _day;
};

int main()
{
	Date d1(1,1);
	Date d2 = { 2,2 };
	return 0;
}

2、static成员

声明为static的类成员称为类的静态成员,用static修饰的成员变量,称之为静态成员变量;用 static修饰的成员函数,称之为静态成员函数静态成员变量一定要在类外进行初始化

例如:实现一个类,计算程序中创建出了多少个类对象。

class A
{
public:
	A() { ++_scount; }

	A(const A& t) { ++_scount; }

	~A() { --_scount; }

	static int GetACount() { return _scount; }

private:
	static int _scount;//这里是声明
};

int A::_scount = 0;

int main()
{
	cout << A::GetACount() << endl;

	A a1, a2;
	A a3(a1);

	cout << A::GetACount() << endl;
	return 0;
}

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

2、静态成员变量必须在类外定义,定义时不添加static关键字,类中只是声明。

3、类静态成员即可用 类名::静态成员 或者 对象.静态成员 来访问。

4、静态成员函数没有隐藏的this指针,不能访问任何非静态成员。

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

3、友元

友元提供了一种突破封装的方式,有时提供了便利。但是友元会增加耦合度,破坏了封装,所以 友元不宜多用。

友元分为:友元函数友元类

3.1、友元函数

问题:现在尝试去重载operator<<,然后发现没办法将operator<<重载成成员函数。因为cout的输出流对象和隐含的this指针在抢占第一个参数的位置。this指针默认是第一个参数也就是左操作数了。但是实际使用中cout需要是第一个形参对象,才能正常使用。所以要将operator<<重载成全局函数。但又会导致类外没办法访问成员,此时就需要友元来解决。operator>>同理。例如:

class Date
{
public:
    Date(int year, int month, int day)
        :_year(year)
        ,_month(month)
        ,_day(day)
    {}

    // d1 << cout; -> d1.operator<<(&d1, cout);  不符合常规调用
    // 因为成员函数第一个参数一定是隐藏的this,所以d1必须放在<<的左侧
    ostream& operator<<(ostream& _cout)
    {
        _cout << _year << "-" << _month << "-" << _day << endl;
        return _cout;
    }

private:
    int _year;
    int _month;
    int _day;
};

int main()
{
    Date d1(1, 1, 1);
    d1 << cout;
    return 0;
}

向上面这种写法肯定是很奇怪的,所以需要用友元来解决。 

友元函数可以直接访问类的私有成员,它是定义在类外部的普通函数,不属于任何类,但需要在 类的内部声明,声明时需要加friend关键字。例如:

class Date
{
	friend ostream& operator<<(ostream& _cout, const Date& d);
	friend istream& operator>>(istream& _cin, Date& d);

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

private:
	int _year;
	int _month;
	int _day;
};
ostream& operator<<(ostream& _cout, const Date& d)
{
	_cout << d._year << "-" << d._month << "-" << d._day;
	return _cout;
}
istream& operator>>(istream& _cin, Date& d)
{
	_cin >> d._year;
	_cin >> d._month;
	_cin >> d._day;
	return _cin;
}
int main()
{
	Date d;
	cin >> d;
	cout << d << endl;
	return 0;
}

注意: 友元函数可访问类的私有和保护成员,但不是类的成员函数。友元函数不能用const修饰。友元函数可以在类定义的任何地方声明,不受类访问限定符限制。一个函数可以是多个类的友元函数。 友元函数的调用与普通函数的调用原理相同。

3.2、友元类

友元类的所有成员函数都可以是另一个类的友元函数,都可以访问另一个类中的非公有成员。友元关系是单向的,不具有交换性。比如:下面的Time类和Date类,在Time类中声明Date类为其友元类,那么可以在Date类中直接访问Time类的私有成员变量,但想在Time类中访问Date类中私有的成员变量则不行。

友元关系不能传递。比如:如果C是B的友元,B是A的友元,则不能说明C是A的友元。

友元关系不能继承(关于继承后面再讲)。

例如:

class Time
{
    friend class Date;  // 声明日期类为时间类的友元类,则在日期类中就直接访问Time类中的私有成员变量

public:
    Time(int hour = 0, int minute = 0, int second = 0)
        : _hour(hour)
        , _minute(minute)
        , _second(second)
    {}

private:
    int _hour;
    int _minute;
    int _second;
};

class Date
{
public:
    Date(int year = 1900, int month = 1, int day = 1)
        :_year(year)
        , _month(month)
        , _day(day)
    {}

    void SetTimeOfDate(int hour, int minute, int second)
    {
        // 直接访问时间类私有的成员变量
        _t._hour = hour;
        _t._minute = minute;
        _t._second = second;
    }

private:
    int _year;
    int _month;
    int _day;
    Time _t;
};

4、内部类

如果一个类定义在另一个类的内部,这个内部类就叫做内部类。内部类是一个独立的类, 它不属于外部类,更不能通过外部类的对象去访问内部类的成员。外部类对内部类没有任何优越的访问权限。

注意:内部类就是外部类的友元类,内部类可以通过外部类的对象参数来访问外部类中的所有成员。但是外部类不是内部类的友元。

特性:

1、内部类可以定义在外部类的public、protected、private都是可以的,定义是可以的,但是仍然会受到访问限定符的限制。

2、内部类可以直接访问外部类中的static成员,不需要外部类的对象或类名。

3、sizeof(外部类)=外部类,和内部类没有任何关系;内部类是独立的,只是受外部类类域的限制并且受访问限定符的限制。

例如:

class A
{
public:
	class B // B天生就是A的友元
	{
	public:
		void foo(const A& a)
		{
			cout << k << endl;//OK
			cout << a.h << endl;//OK
		}
	};

private:
	static int k;
	int h;
};

int A::k = 1;

int main()
{
	A::B b;//若想定义B类这样才行。

	b.foo(A());

	return 0;
}

5、匿名对象

匿名对象的特点,生命周期只有一行,具有常性。

const引用会延长匿名对象的生命周期,本质上相当于匿名对象有名字了。例如:

const A& ref = A();

当ref出作用域后,匿名对象也就销毁了。

例如:

class A
{
public:
	A(int a = 0)
		:_a(a)
	{
		cout << "A(int a)" << endl;
	}

	~A()
	{
		cout << "~A()" << endl;
	}

private:
	int _a;
};

class Solution 
{
public:
	int Sum_Solution(int n) {
		//...
		return n;
	}
};

int main()
{
	A aa1;
    // 匿名对象的特点不用取名字,但是他的生命周期只有这一行,我们可以看到下一行他就会自动调用析构函数。
	A();

	A aa2(2);
	// 匿名对象在这样场景下就很好用,当然还有一些其他使用场景,这个我们以后遇到了再说。
	Solution().Sum_Solution(10);//也就是说匿名对象对于即用即销毁的情况下比较方便。

	return 0;
}

6、拷贝对象时的优化(了解)

在传参和传返回值的过程中,一般编译器会做一些优化,减少对象的拷贝,这个在一些场景下还 是非常有用的。

例如:连续的构造或者拷贝构造会被编译器优化

class A
{
public:
	A(int a = 0)
		:_a(a)
	{
		cout << "A(int a)" << endl;
	}

	A(const A& aa)
		:_a(aa._a)
	{
		cout << "A(const A& aa)" << endl;
	}

	A& operator=(const A& aa)
	{
		cout << "A& operator=(const A& aa)" << endl;
		if (this != &aa)
		{
			_a = aa._a;
		}
		return *this;
	}

	~A()
	{
		cout << "~A()" << endl;
	}

	void Print()
	{
		cout << "Print()->" << _a << endl;
	}

private:
	int _a;

};
void f1(A aa)
{
	aa.Print();
}

int main()
{
	
	A aa1;
	f1(aa1);

	cout << "--------------------------------" << endl;
	f1(A(1));//优化为了直接构造

	cout << "--------------------------------" << endl;
	f1(1);//优化为了直接构造。

	cout << "--------------------------------" << endl;
	A aa2 = 1;//优化为了直接构造

	cout << "--------------------------------" << endl;
	A aa3 = A(2);//优化为了直接构造


	return 0;
}

例如:

class A
{
public:
	A(int a = 0)
		:_a(a)
	{
		cout << "A(int a)" << endl;
	}

	A(const A& aa)
		:_a(aa._a)
	{
		cout << "A(const A& aa)" << endl;
	}

	A& operator=(const A& aa)
	{
		cout << "A& operator=(const A& aa)" << endl;
		if (this != &aa)
		{
			_a = aa._a;
		}
		return *this;
	}

	~A()
	{
		cout << "~A()" << endl;
	}

	void Print()
	{
		cout << "Print()->" << _a << endl;
	}

private:
	int _a;
};

A f2()
{
	A aa;
	return aa;
}

int main()
{
	A ret1=f2();//优化为了直接构造

	cout << "---------------------------" << endl;
	A ret2;
	ret2 = f2();//只优化了一次拷贝构造

	return 0;
}

例如:

class A
{
public:
	A(int a = 0)
		:_a(a)
	{
		cout << "A(int a)" << endl;
	}

	A(const A& aa)
		:_a(aa._a)
	{
		cout << "A(const A& aa)" << endl;
	}

	A& operator=(const A& aa)
	{
		cout << "A& operator=(const A& aa)" << endl;
		if (this != &aa)
		{
			_a = aa._a;
		}
		return *this;
	}

	~A()
	{
		cout << "~A()" << endl;
	}

	void Print()
	{
		cout << "Print()->" << _a << endl;
	}

private:
	int _a;
};

A f2()
{
	return A(1);
}

A f3()
{
	return 1;
}

int main()
{
	A ret1=f2();//优化为了直接构造

	cout << "----------------------" << endl;
	A ret2 = f3();//优化为了直接构造

	return 0;
}

注意:这一块的优化取决与编译器,不同的编译器优化的情况是不同的。

7、重新理解类与对象

现实生活中的实体计算机并不认识,计算机只认识二进制格式的数据。如果想要让计算机认识现 实生活中的实体,用户必须通过某种面向对象的语言,对实体进行描述,然后通过编写程序,创 建对象后计算机才可以认识。

比如想要让计算机认识洗衣机,就需要:

1、用户先要对现实中洗衣机实体进行抽象---即在人为思想层面对洗衣机进行认识,洗衣机有什么属性,有那些功能,即对洗衣机进行抽象认知的一个过程。

2、经过1之后,在人的头脑中已经对洗衣机有了一个清醒的认识,只不过此时计算机还不清楚,想要让计算机识别人想象中的洗衣机,就需要人通过某种面相对象的语言(比如:C++、 Java、Python等)将洗衣机用类来进行描述,并输入到计算机中。

3、经过2之后,在计算机中就有了一个洗衣机类,但是洗衣机类只是站在计算机的角度对洗衣机对象进行描述的,通过洗衣机类,可以实例化出一个个具体的洗衣机对象,此时计算机才能知道洗衣机是什么东西。

4、用户就可以借助计算机中洗衣机对象,来模拟现实中的洗衣机实体了。

在类和对象阶段,一定要体会到,类是对某一类实体(对象)来进行描述的,描述该对象具有哪些属性,哪些方法,描述完成后就形成了一种新的自定义类型,才用该自定义类型就可以实例化具体的对象。在面向对象这一块,更多关注的是类与类之间的关系。

8、日期类的实现

日期类的实现,作为类的练习。

Date.h

#include<iostream>
using namespace std;
#include<assert.h>

class Date
{
	//友元;有了友元就可以让这个函数访问类的私有属性。
	friend ostream& operator<<(ostream& out, const Date& d);
	friend istream& operator>>(istream& in, Date& d);

public:
	Date(int year = 1900, int month = 1, int day = 1);//构造函数

	void Print() const;

	int GetMonthDay(int year, int month) const;

	//运算符重载
	bool operator==(const Date& d) const;
	bool operator!=(const Date& d) const;
	bool operator<(const Date& d) const;
	bool operator<=(const Date& d) const;
	bool operator>(const Date& d) const;
	bool operator>=(const Date& d) const;

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


	int operator-(const Date& d) const;//跟上面的-构成重载了。

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

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

	/*void operator<<(ostream& out);*/

private:
	int _year;
	int _month;
	int _day;
};


ostream& operator<<(ostream& out, const Date& d);

istream& operator>>(istream& in, Date& d);

Date.cpp

#include"Date.h"


int Date::GetMonthDay(int year, int month) const
{
	assert(month >= 0 && month < 13);

	int monthday[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
	if (month == 2 && (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
	{
		return 29;
	}
	else
	{
		return monthday[month];
	}
}


Date::Date(int year, int month, int day)
{
	if (month > 0 && month < 13 && (day > 0 && day <= GetMonthDay(year, month)))
	{
		_year = year;
		_month = month;
		_day = day;
	}
	else
	{
		cout << "日期非法" << endl;
	}
}


void Date::Print() const
{
	cout<<_year<<'/'<<_month<<'/'<<_day<<endl;
}


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


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


bool Date::operator<=(const Date& d) const
{
	return *this < d || *this == d;//利用了上面两个运算符重载。
}


bool Date::operator>(const Date& d) const
{
	return !(*this <= d);
}


bool Date::operator>=(const Date& d) const
{
	return !(*this < d);
}


bool Date::operator!=(const Date& d) const
{
	return !(*this == d);
}


Date& Date::operator+=(int day)//出作用域this还在,可以用引用返回
{
	if (day < 0)
	{
		*this -= -day;
		return *this;
	}
	_day += day;
	while (_day > GetMonthDay(_year, _month))
	{
		_day -= GetMonthDay(_year, _month);
		_month++;
		if (_month == 13)
		{
			++_year;
			_month = 1;
		}
	}

	return *this;
}


Date Date::operator+(int day) const//出了作用域tmp不在,所以不可以使用引用返回。
{
	Date tmp(*this);

	tmp += day;

	return tmp;
}

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


Date Date::operator-(int day) const
{
	Date tmp(*this);
	tmp -= day;
	return tmp;
}


//在自定义类型这一块,前置++的效率要高于后置++
//在内置类型这一块前置和后置没有区别。
Date& Date::operator++()
{
	*this += 1;
	return *this;
}

Date Date::operator++(int)
{
	Date tmp(*this);
	*this += 1;

	return tmp;
}


Date& Date::operator--()
{
	*this -= 1;
	return *this;
}


Date Date::operator--(int)
{
	Date tmp(*this);
	*this -= 1;

	return tmp;
}


int Date::operator-(const Date& d) const
{
	Date max = *this;
	Date min = d;
	int flag = 1;

	if (*this < d)
	{
		max = d;
		min = *this;
		flag = -1;
	}
	int n = 0;
	while (min != max)
	{
		++min;
		++n;
	}
	return n * flag;
}

//返回值是为了支持连续输入和输出。
ostream& operator<<(ostream& out, const Date& d)//这里不一定非要使用友元,也可以在类里面写一些能得到私有属性的函数,从而得到私有属性。
{
	out << d._year << "年" << d._month << "月" << d._day << "日" << endl;

	return out;
}

istream& operator>>(istream& in, Date& d)
{
	in >> d._year >> d._month >> d._day;

	return in;
}

9、练习题

9.1、第一题

链接:求1+2+3+...+n

 参考:

class Sum
{
public:
    Sum()
    {
        _sum += _i;
        _i++;
    }
    static int GetSum()
    {
        return _sum;
    }
private:
    static int _i;
    static int _sum;
};

int Sum::_i = 1;
int Sum::_sum = 0;

class Solution {
public:
    int Sum_Solution(int n) {
        Sum a[n];
        return Sum::GetSum();
    }
};

9.2、第二题

链接:计算日期到天数的转换

9.3、第三题

链接:日期差值 

9.4、第四题

链接:打印日期 

9.5、第五题

链接:日期累加

相关文章:

  • 如何在React中集成 PDF.js?构建支持打印下载的PDF阅读器详解
  • mapbox基础,加载栅格图片到地图
  • QMT实盘代码案例教学:etf全球配置策略
  • 深入理解Java性能调优与JVM底层机制
  • 柯尼卡美能达CA-410-CA-VP427 P427
  • 从 “单打独斗” 到 “生态共赢” 跨境货源池的协同增长逻辑
  • 摄像头模块对焦方式的类型
  • Java基础 4.7
  • 基于Python的二手房数据挖掘与可视化深度分析
  • STM32单片机入门学习——第22节: [7-2] AD单通道AD多通道
  • AutoAgent: 香港大学开源的AI智能体框架
  • ARM-IIC
  • #简易线程池...实现原理
  • 从零开始的图论讲解(1)——图的概念,图的存储,图的遍历与图的拓扑排序
  • ubuntu 20.04 编译和运行A-LOAM
  • std::async 和 std::thread 的主要区别
  • 使用Vue、Nodejs以及websocket搭建一个简易聊天室
  • 项目难点亮点
  • 国密算法(SM2/SM3/SM4)与国际算法(AES/RSA/SHA-256)
  • 数据集的训练-测试拆分在机器学习中的重要性
  • 网站做百度竞价/网络营销是什么?
  • 网站设计美工要怎么做/爱站网关键词长尾挖掘
  • 网页设计与网站开发的实践目的/百度一下首页官网下载
  • 学校网站建设介绍范文/seo推广和百度推广的区别
  • 做网站日ip100/百度一下下载
  • 公司要建设网站需要那些程序/山西seo关键词优化软件搜索