1. 定义一个Cat类,拥有静态数据成员 numOfCats,记录Cat的个体数目; 静态成员函数getNumOfCats(),读取numOfCats。设计程序测试这个类,体会静态数据成员和静态成员函数的用法。
#include <iostream>
#include <cstring>
using namespace std;
class Cat
{
private:
static int numOfCats;
char m_name[20];
public:
void SetCat(char *name);
static int GetNumOfCats()
{
cout << "猫有" << numOfCats << "只!" << endl;
}
void Quit(int temp);
};
void Cat::SetCat(char *name)
{
cout << "输入猫的名字!" << endl;
cin >> name;
strcpy(m_name, name);
numOfCats++;
}
void Cat::Quit(int temp)
{
temp = 0;
cout << "输入:0——继续录入;1——停止录入" << endl;
cin >> temp;
if (temp == 1)
{
cout << "停止录入!";
Cat::GetNumOfCats();
exit(1);
}
}
int Cat::numOfCats = 0;
int main()
{
char name[20];
int cat[30];
int temp = 0;
for (int i = 0; i < 30; i++)
{
Cat cat[i];
cat[i].SetCat(name);
cat[i].Quit(temp);
}
Cat::GetNumOfCats();
return 0;
}
2. 在函数fn1()中定义一个静态变量n, fn1()中对n的值加1,在主函数中,调用fn1()十次,显示n的值。
#include <iostream>
using namespace std;
void fn1()
{
static int n = 0;
cout << "fn1被调用!" << endl;
n++;
cout << "n的结果为:" << n << endl
<< endl;
}
int main()
{
for (int i = 0; i < 10; i++)
{
fn1();
}
return 0;
}
3. 定义类X, Y, Z,函数h(X*),类X有私有成员i,Y的公有成员函数g(X*)是X的友元函数,实现对X的成员i加1;类Z是类X的友元类,其成员函数f(X*)实现对X的成员i加5;函数h(X*)是X的友元函数,实现对X的成员i加10。在一个文件中定义和实现类,在另一个文件中完成main()函数。
- XYZ.h
#include "XYZ.h"
X::X(int i) : i(0)
{
cout << "i的初值为" << i << endl;
}
void X::add(int num)
{
i += num;
cout << "i = " << i << endl;
}
void Y::g(X *a)
{
a->add(1);
}
void Z::f(X *a)
{
a->add(5);
}
void h(X *a)
{
a->add(10);
}
- XYZ.cpp
#include "XYZ.h"
X::X(int i) : i(0)
{
cout << "i的初值为" << i << endl;
}
void X::add(int num)
{
i += num;
cout << "i = " << i << endl;
}
void Y::g(X *a)
{
a->add(1);
}
void Z::f(X *a)
{
a->add(5);
}
void h(X *a)
{
a->add(10);
}
- main.cpp
#include "XYZ.h"
int main()
{
X x;
Y y;
Z z;
h(&x);
y.g(&x);
z.f(&x);
return 0;
}
4. 定义Boat与Car两个类,二者都有weight属性,定义二者的一个友元函数getTotalWeight, 计算二者的重量之和
#include <iostream>
using namespace std;
class Car;
class Boat
{
private:
float weight;
public:
Boat(float w) : weight(w) {}
~Boat() {}
Boat(Boat &b) : weight(b.weight) {}
friend void getTotalWeight(Boat &b, Car &c);
};
class Car
{
private:
float weight;
public:
Car(float w) : weight(w) {}
~Car() {}
Car(Car &b) : weight(b.weight) {}
friend void getTotalWeight(Boat &b, Car &c);
};
void getTotalWeight(Boat &b, Car &c)
{
float sum = b.weight + c.weight;
cout << "总重量为:" << sum << "t!" << endl;
}
int main()
{
Boat b(34.2);
Car c(4.3);
getTotalWeight(b, c);
return 0;
}
|