Complexoperator+(Complex&c1,Complex&c2)
{
Complexc;
c.real=c1.real+c2.real;
c.imag=c1.imag+c2.imag;
returnc;
}
Complexoperator-(Complex&c1,Complex&c2)
{
Complexc;
c.real=c1.real-c2.real;
c.imag=c1.imag-c2.imag;
returnc;
}
intmain()
{
Complexc1(3,4),c2(5,-10),c3,c4;
c1.display();
c2.display();
c3=c1+c2;
cout<<"c3=c1+c2=";
c3.display();
c4=c1-c2;
cout<<"c4=c1-c2=";
c4.display();
return0;
}
5-7
#include
using namespace std;
class Cat { public:
Cat(int age){numOfCats++; }
virtual ~Cat() { numOfCats--; }
static int getnumOfCats() { return numOfCats; } private:
static int numOfCats; };
int Cat:
:
numOfCats = 0; void telepathicFunction() { cout << "There are " << Cat:
:
getnumOfCats() << " cats alive!
\n"; }
int main() {
const int maxCats = 5;
Cat *catHouse[maxCats]; int i;
for (i = 0; i < maxCats; i++) { catHouse[i] = new Cat(i); telepathicFunction(); }
for (i = 0; i < maxCats; i++) { delete catHouse[i]; telepathicFunction(); }
return 0; }
4-11
#include
class Rectangle
{
public:
Rectangle(float len, float width)
{
Length = len;
Width = width;
}
~Rectangle(){};
float GetArea() { return Length * Width; }
float GetLength() { return Length; }
float GetWidth() { return Width; }
private:
float Length;
float Width;
};
void main()
{
float length, width;
cout << "请输入矩形的长度:
";
cin >> length;
cout << "请输入矩形的宽度:
";
cin >> width;
Rectangle r(length, width);
cout << "长为" << length << "宽为" << width << "的矩形的面积为:
"
<< r.GetArea () << endl;
}
3、编写一个类,其成员函数包括:
1)接受键盘输入的英文句子;2)实现一条英文句子中字母的个数统计并输出;3)输出英文句子。
主函数里进行测试。
#include
usingnamespacestd;
classChar
{
public:
Char(){count=0;}
voidInput();
voidshow();
voidGetCount()
{
cout<<"字母个数为:
"<}
private:
chara[100];
intcount;
};
voidChar:
:
Input()
{
for(inti=0;i<100;i++)
{
count++;
cin>>a[i];
if(a[i]=='@')//当输入的符合为@是退出循环
break;
}
}
voidChar:
:
show()
{
for(inti=0;icout<cout<}
intmain(){
Chara;
a.Input();
a.show();
a.GetCount();
return0;}