学习c++对类的6个成员函数的简单总结

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Cell_KEY/article/details/51577054

首先我们对c++中类的6个默认成员有个概念上的理解,以下是对其的简单总结,在简单了解之后通过简单的程序例子在具体看它如何使用

在通过以上的简单了解之后我们对6个成员函数有了初步的认识,接下 来看看他在具体例子中的实现

以下是创建了一个日期类,其中包含了个小功能就是“可以求出函数运行时间”,原理是:在一个对象的生命周期内只调用一次构造函数和析构函数,并且在对象生成时调用的是构造函数,在对象被销毁时需要调用析构函数,所以我们在构造函数记住一个时间,在析构函数记住一个时间就可以求出函数的运行时间了。

#include <iostream>
#include<time.h>
using namespace std;
clock_t tick2, tick1;
class Date
{
	
public:
	Date(int year=0, int month=0, int day=0);//构造函数
	Date(const Date & c)//拷贝构造函数
	{
		_year = c._year;
		_month = c._month;
		_day = c._day;
	}
	~Date();
	Date & operator=(const Date &c)//赋值运算符重载
	{
			if (this != &c)
			{
				_year = c._year;
				_month = c._month;
				_day = c._day;
			}
			return *this;
		}
void print();
private:
	int _year;
	int _month;
	int _day;
	//Time t;
};
 
Date::Date(int year , int month , int day )
:_year(year)
, _month(month)
, _day(day)
{
	tick1 = clock();
}
Date::~Date()
{
	tick2 = clock();
	cout << tick2 - tick1 << endl;
}
void Date::print()
{
	cout << _year << "-" << _month << "-" << _day << endl;
}
void test1()
{
	Date s1(2016, 5, 27);
	s1.print();
	Date s2(s1);
}

int main()
{
	int a;
	test1();
	cin >> a;
	return 0;
}
还有就是构造函数、拷贝构造函数、析构函数可以在类内声明类外定义,在类外定义时要用类的作用域限制符修饰,保证它是属于类内的,也可以在类内直接定义,而赋值运算符就只能在类内定义

猜你喜欢

转载自blog.csdn.net/Cell_KEY/article/details/51577054