【关于类的练习】

1、计算一个类创建了多少个对象

#include<iostream>
using namespace std;

class temp
{
	static int a;
public:
	temp()
	{
		++a;
	}
	temp(const temp& b)
	{
		++a;
	}
	 static int GetA()
	{
		 return a;
	}
};
int temp::a = 0;
int main()
{
	cout << temp::GetA() << endl;
	temp a;
	temp b;
	temp c;
	temp d(a);
	cout << temp::GetA() << endl;
	system("pause");
	return 0;
}

2、求1+2+3+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)

#include<iostream>
using namespace std;

class Solution 
{
public:
	int Sum_Solution(int n) 
	{
		int a = 1, b = a + 1;
		while (b <= n)
		{
			int c = b;
			while (b!=0)//执行加法
			{
					int c = a^b;//不加进位的
					b = (a&b) << 1;//进位
					a = c;
			}
			b=c;
			++b;
		}
		return a;
     }
};

int main()
{
	Solution a;
	int n = 3;
	cout<<a.Sum_Solution(n)<<endl;
	system("pause");
	return 0;
}

3、给定年月日判断这一天是这一年的第几天?

#include<iostream>
using namespace std;


class Date
{
public:
	int GetMonthDay(int year, int month)
	{
		int monthDays[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)))
			//是闰年,二月29天
		{
			return 29;
		}
		return monthDays[month];//是几月就返回该月的天数
	}
	Date(int year, int month, int day)
	{
		if (year > 0 && (month >= 1 && month <= 12) && (day >= 1 && day <= GetMonthDay(year, month)))
		{
			_year = year;
			_month = month;
			_day = day;
		}
		else
		{
			cout << "非法日期" << endl;
		}
	}
	int GetDayofYear()
	{
		int sum = 0;
		if (_month==1)
		{
			return _day;
		}
		else
		{
			for (int i = 1; i < _month; i++)
			{
				sum += GetMonthDay(_year, i);
			}
			sum += _day;
		}
		return sum;
	}
private:
	int _year;
	int _month;
	int _day;
};

int main()
{
	int year, month, day;
	while (cin >> year >> month >> day)
	{
		Date a(year, month, day);
		cout<<a.GetDayofYear()<<endl;
	}
	system("pause");
	return 0;
}

问题:

1、类的构造顺序和析构顺序是什么样的?
在这里插入图片描述

先构造全局的的C类的类对象,再依次构造A和B类的对象,静态局部对象,执行到它时才能开始初始化它,所以构造顺序是:C,A,B,D;
析构:先析构B,A,再析构静态对象,最后析构全局对象

2、(没有考虑编译器的优化)

在这里插入图片描述

一般情况下认为是9次,但是编译器会进行优化
在这里插入图片描述编译器优化后是7次
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值