一、断言和静态断言
#include<iostream>
#include<array>
#include<cassert> //使用assert()断言必须包含的头文件
using std::cout;
using std::endl;
//任务1:用递归计算factorial,用assert检查3的竭诚
//任务2:将factorial变成常量表达式,用static_assert检查3的阶乘;
//任务3:创建factorial(4)大小的数组
//注释:静态断言会在编译期就进行判断
constexpr int factorial(int n)
{
if (n == 0)
{
return 1;
}
else
{
return n * factorial(n - 1);
}
}
int main()
{
static_assert((factorial(4) == 24), "factorial(4) shou be 24");
std::array<int, factorial(4) >a;
cout << a.size();
std::cin.get();
return (0);
}
结果如上图所示
二、静态成员函数
#include<iostream>
#include<cassert>
//任务1:创建Square类
class Square
{
private:
double side{ 1.0 };
static int numberOfObjects;
public:
double getSide() { return side; }
void setSide(double side) { this->side = side; }
Square(double side)
{
this->side = side;
numberOfObjects++;
}
Square() :Square(1.0) {}
double getArea() { return side * side; }
static int getNumberOfObjects() { return numberOfObjects; }
int getNumberOfObjectsNonStatic() { return numberOfObjects; }
};
int Square::numberOfObjects = 10;
int main()
{
Square s1;
std::cout << s1.getNumberOfObjects() << std::endl;
assert(s1.getNumberOfObjects() == 11);
Square s2{ 20.0 };
std::cout << Square::getNumberOfObjects() << std::endl;
std::cout << s2.getNumberOfObjectsNonStatic() << std::endl;
//std::cout << Square::getNumberOfObjectsNonStatic() << std::endl;
//类中非静态成员函数不可用 ::来获取
std::cin.get();
return 0;
}
结果如上图所示。