//sy4_1.cpp
#include<iostream>
using namespace std;
class My
{
public:
My(int aa)
{
A=aa;
B-=aa;
}
static void fun(My m);
private:
int A;
static int B;
};
void My::fun(My m)
{
cout<<"A="<<m.A<<endl;
cout<<"B="<<B<<endl;
}
int My::B=100;
int main()
{
My p(6),Q(8); //语句1
My::fun(p);
Q.fun(Q);
return 0;
}
(1)指出所有的构造函数,它们在本程序中分别起什么作用?
第一个构造函数My(double i=0)用来初始化对象m1和m2 ,第二个构造函数My(double i,double j)用来初始化对象m3 。拷贝构造函数My(My&m)用来初始化对象m4。
(2)指出设置默认参数的构造函数。
默认参数的构造函数是My(double i=0)。
(3)指出友元函数,将友元函数放在私有部分,观察结果是否有变化。
友元函数是dist()为,将dist()放到私有部分,编译程序发现结果仍然是正确的。这是因为友元函数是一个在类里声明的普通函数,声明位置可在类的任何部位,即可在public区也可在private区和protected区,意义完全一样,因此编译时不会出错。
(4)写出输出结果,并分析输出结果。
//sy4_2.cpp
#include<iostream>
#include<cmath>
using namespace std;
class My
{
public:
My(double i=0){x=y=i;}
My(double i,double j){x=i;y=j;}
My(My&m){x=m.x;y=m.y;}
friend double dist(My&a,My&b);
private:
double x,y;
};
double dist(My&a,My&b)
{
double dx=a.x-b.x;
double dy=a.y-b.y;
return sqrt(dx*dx+dy*dy);
}
int main()
{
My m1,m2(15),m3(13,14);
My m4(m3);
cout<<"The distance1:"<<dist(m1,m3)<<endl;
cout<<"The distance2:"<<dist(m2,m3)<<endl;
cout<<"The distance3:"<<dist(m3,m4)<<endl;
cout<<"The distance4:"<<dist(m1,m2)<<endl;
return 0;
}
结果:
分析:友元函数dist()的主要作用是求两点之间的距离。
3.定义一个Student类,在该类定义中包括一个数据成员score(分数)、两个静态数据成员total(总分)和学生人数count;成员函数scoretotalcount(float s)用于设置分数、求总分和累计学生人数;静态成员函数sum()用于返回总分;静态成员函数average()用于求平均值。在main()函数中,输入某班同学的成绩,并调用上述函数求全班学生的总分和平均分。(sy4_3.cpp)
编写程序如下:
//sy4_3.cpp
#include<iostream>
using namespace std;
class student
{
public:
void scoretotalcount(float s);
static float sum();
static float average();
private:
float score;
static float total;
static int count;
};
float student::total=0;
int student::count=0;
void student::scoretotalcount(float s)
{
score=s;
total+=score;
count++;
}
float student::sum(){return total;}
float student::average(){return total/count;}
int main()
{
float s;
int n;
student a[8];
cout<<"请输入学生的人数:";
cin>>n;
cout<<"请输入学生成绩:";
for(int i(0);i<n;i++)
{
cin>>s;
a[i].scoretotalcount(s);
}
cout<<"全班学生的总分为:";
cout<<student::sum()<<endl;
cout<<"全班学生的平均分为:";
cout<<student::average()<<endl;
return 0;
}
4、声明Book与Ruler两个类,二者都有weight属性,定义二者的一个友元函数totalWeight(),计算二者的重量和。(sy4_4.cpp)
编写程序如下:
//sy4_4.cpp
#include<iostream>
using namespace std;
class Ruler;
class Book
{
public:
Book(int x){weight=x;}
friend int totalWeight(Book&book,Ruler&ruler);
private:
int weight;
};
class Ruler
{
public:
Ruler(int x){weight=x;}
friend int totalWeight(Book&book,Ruler&ruler);
private:
int weight;
};
int totalWeight(Book&book,Ruler&ruler)
{
return book.weight+ruler.weight;
}
int main()
{
float x,y;
cout<<"请输入“Book weight”:";
cin>>x;
cout<<"请输入“Ruler weight”:";
cin>>y;
Book B(x);
Ruler R(y);
cout<<"totalweight:"<<totalWeight(B,R)<<endl;
return 0;
}