编程语言
首页 > 编程语言> > c++在类的声明中初始化私有成员变量

c++在类的声明中初始化私有成员变量

作者:互联网

c++在类的声明中初始化私有成员变量

class Time
{
private:
	int hours = 3;   //c++ 11 允许这样的定义
	int mins = 2;
public:
	Time(int = 2, int = 3);
	Time(const Time & a);
	~Time();
	void show();
	Time operator+(const Time & a)const;

};
#include <iostream>
#include"time.h"
using namespace std;

Time::Time(int h, int m)
{
	hours = h;
	mins = m;
}
Time::Time(const Time & a)
{
	hours = a.hours;
	mins = a.mins;
}
Time::~Time()
{
	cout << "Time is over " << hours << mins << endl;
}
Time Time:: operator+(const Time & a)const
{
	Time sum;
	sum.hours = hours + a.hours;
	sum.mins = mins + a.mins;
	return sum;
}
void Time::show()
{
	cout << hours << "," << mins << endl;
}
int main()
{
	Time old;
	Time new1(1, 2);
	Time new2(new1);
	old.show();
	new1.show();
	Time haha = old + new1;
	haha.show();
	new2.show();
}

结果

标签:初始化,const,show,私有,c++,hours,int,Time,mins
来源: https://blog.csdn.net/j15941558855/article/details/121315837