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次