国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

C++習題與解析(重載-03)

2019-11-17 05:44:13
字體:
來源:轉載
供稿:網友

題1.分析以下程序的執行結果
#include<iostream.h>
int add(int x,int y)
{
return x+y;
}
int add(int x,int y,int z)
{
return x+y+z;
}
void main()
{
int a=4,b=6,c=10;
cout<<add(a,b)<<","<<add(a,b,c)<<endl;
}
解:
本題說明重載函數的使用方法。這里有兩個add()函數,一個的參數是2個,另一個的參數是3個,它們是根據參數個數自動區分的。
所以輸出為: 10,20

-------------------------------------------------

題2.分析以下程序的執行結果
#include<iostream.h>
class Sample
{
int i;
double d;
public:
void setdata(int n){i=n;d=0;}
void setdata(int n,double x)
{
i=n;d=x;
}
void disp()
{
cout<<"i="<<i<<",d="<<d<<endl;
}
};
void main()
{
Sample s;
s.setdata(10);
s.disp();
s.setdata(2,15.6);
s.disp();
}
解:
本題說明重載函數的使用方法。setdata()成員函數有2個,根據其參數個數自動加以區分。
所以輸出為:
i=10,d=0
i=2,d=15.6

------------------------------------------------

題3.分析以下程序的執行結果
#include<iostream.h>
class Sample
{
int n;
public:
Sample(){}
Sample(int i){n=i;}
friend Sample Operator-(Sample &,Sample &);
friend Sample operator+(Sample &,Sample &);
void disp(){cout<<"n="<<n<<endl;}
};
Sample operator-(Sample &s1,Sample &s2)
{
int m=s1.n-s2.n;
return Sample(m);
}
Sample operator+(Sample &s1,Sample &s2)
{
int m=s1.n+s2.n;
return Sample(m);
}
void main()
{
Sample s1(10),s2(20),s3;
s3=s2-s1;
s3.disp();
s3=s2+s1;
s3.disp();
}
解:
本題說明重載運算符-和+的使用。operator-和operator+兩個友元函數實現兩個對象的減法和加法。所以輸出為:
n=10 // s2-s1
n=30 // s2+s1

---------------------------------------------------

題4.分析以下程序的執行結果
#include<iostream.h>
class Sample
{
int A[10][10];
public:
int &operator()(int,int);
};
int &Sample::operator()(int x,int y)
{
return A[x][y];
}
void main()
{
Sample a;
int i,j;
for(i=0;i<10;i++)
for(j=0;j<10;j++)
a(i,j)=i+j;
for(i=0;i<10;i++)
cout<<a(i,1)<<" ";
cout<<endl;
}
解:
本題說明重載下標運算符的使用方法。通過重載下標運算符,使得對于對象a,有a(i,j)等于a.A[i][j]。

所以輸出為: 1 2 3 4 5 6 7 8 9 10

------------------------------------------------

題5.分析以下程序的執行結果
#include<iostream.h>
class Sample
{
int n;
public:
Sample(int i){n=i;}
operator++(){n++;} // 前綴重載運算符
operator++(int){n+=2;} // 后綴重載運算符
void disp()
{
cout<<"n="<<n<<endl;
}
};
void main()
{
Sample A(2),B(2);
A++; // 調用后綴重載運算符
++B; // 調用前綴重載運算符
A.disp();
B.disp();
}
解:
本題說明重載運算符++的使用方法。operator++()為前綴重載運算符,operator++(int)為后綴重載運算符。A++的語句調用后綴重載運算符,++B語句調用前綴重載運算符。
所以輸出為:
n=4
n=3




發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 武平县| 江华| 宁城县| 微博| 哈尔滨市| 光泽县| 北宁市| 天祝| 封丘县| 保德县| 武汉市| 永春县| 思南县| 富川| 嘉善县| 钦州市| 巧家县| 岐山县| 洱源县| 富裕县| 江城| 濮阳市| 麦盖提县| 通海县| 浙江省| 普格县| 昆山市| 治县。| 西乡县| 西畴县| 宣汉县| 永仁县| 苍梧县| 江永县| 磐安县| 贵定县| 罗田县| 德江县| 吉木乃县| 长泰县| 思茅市|