第二章 測驗(代碼自己測試)
有類A如下定義:
class A {
int v;
public:
A ( int n) { v = n; }
};
下面哪條語句是編譯不會出錯的?
-
A.
D) A a1(3);
-
B.
C) A * p = new A();
-
C.
A) A a = new A();
-
D.
B) A a2;
假設 A 是一個類的名字,下面的語句生成了幾個類A的對象?
A * arr[4] = { new A(), NULL,new A() };
-
A.
B) 2
-
B.
D) 4
-
C.
C) 3
-
D.
A) 1
假設A 是一個類的名字,下面哪段程序不會用到A的復制構造函數?
-
A.
A) A a1,a2; a1 = a2;
-
B.
B) void func( A a) { cout << "good" << endl; }
-
C.
C) A func( ) { A tmp; return tmp; }
-
D.
D) A a1; A a2(a1);
類A定義如下:
class A {
int v;
public:
A(int i) { v = i; }
A() { }
};
下面哪段程序不會引發類型轉換構造函數被調用?
-
A.
A) A a1(4)
-
B.
B) A a2 = 4;
-
C.
C) A a3; a3 = 9;
-
D.
D) A a1,a2; a1 = a2;
假設A是一個類的名字,下面的程序片段會調用類A的調用析構函數幾次?
int main() {
A * p = new A[2];
A * p2 = new A;
A a;
delete [] p;
}
-
A.
C) 3
-
B.
D) 4
-
C.
A) 1
-
D.
B) 2
6,編程填空:學生信息處理程序
實現一個學生信息處理程序,計算一個學生的四年平均成績。
要求實現一個代表學生的類,並且類中所有成員變量都是【私有的】。
補充下列程序中的 Student 類以實現上述功能。
輸入:
輸入數據為一行,包括:
姓名,年齡,學號,第一學年平均成績,第二學年平均成績,第三學年平均成績,第四學年平均成績。
其中姓名為由字母和空格組成的字符串(輸入保證姓名不超過20個字符,並且空格不會出現在字符串兩端),年齡、學號和學年平均成績均為非負整數。信息之間用逗號隔開。
輸出:
輸出一行數據,包括:
姓名,年齡,學號,四年平均成績。
信息之間用逗號隔開。
樣例輸入
Tom Hanks,18,7817,80,80,90,70
樣例輸出
Tom Hanks,18,7817,80
提示
必須用類實現,其中所有成員變量都是私有的。
輸出結果中,四年平均成績不一定為整數。
#include <iostream>
#include <string>
#include <cstdio>
#include <cstring>
#include <sstream>
#include <cstdlib>
using namespace std;
class Student {
private:
char name[23];
int age;
int xuehao;
int score1,score2,score3,score4;
double ave;
public:
void input(){
scanf("%[^,],%d,%d,%d,%d,%d,%d",name,&age,&xuehao,&score1,&score2,&score3,&score4);
}
void calculate(){
ave=(score1+score2+score3+score4)/4.0;
}
void output(){
printf("%s,%d,%d,%g",name,age,xuehao,ave);
}
};
int main() {
Student student; // 定義類的對象
student.input(); // 輸入數據
student.calculate(); // 計算平均成績
student.output(); // 輸出數據
}
7,奇怪的類復制
程序填空,使其輸出9 22 5
#include <iostream>
using namespace std;
class Sample {
public:
int v;
Sample(int n=0)
{
v=n;
}
Sample(const Sample &x)
{
v=x.v+2;
}
};
void PrintAndDouble(Sample o)
{
cout << o.v;
cout << endl;
}
int main()
{
Sample a(5);
Sample b = a;
PrintAndDouble(b);
Sample c = 20;
PrintAndDouble(c);
Sample d;
d = a;
cout << d.v;
return 0;
}
8,超簡單的復數類
下面程序的輸出是:
3+4i
5+6i
請補足Complex類的成員函數。不能加成員變量。
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
class Complex {
private:
double r,i;
public:
void Print() {
cout << r << "+" << i << "i" << endl;
}
Complex& operator = (const char* s)
{
string str = s;
int pos = str.find("+", 0);
string strReal = str.substr(0, pos);
r = atof(strReal.c_str());
string strImaginary = str.substr(pos + 1, str.length() - pos - 2);
i = atof(strImaginary.c_str());
return *this;
}
};
int main() {
Complex a;
a = "3+4i"; a.Print();
a = "5+6i"; a.Print();
return 0;
}
9.哪來的輸出
程序填空,輸出指定結果 2 1
#include <iostream>
using namespace std;
class A {
public:
int i;
A(int x) { i = x; }
~A()
{
cout<<i<<endl;
}
};
int main()
{
A a(1);
A * pa = new A(2);
delete pa;
return 0;
}