?? 第三章部分習題.txt
字號:
第三章 類和對象部分習題
3.18 指出下列程序中的錯誤,并說明為什么。
#include <iostream.h>
class Student{
char name[10];
int age;
float aver;
void printStu();
};
void main()
{
Student p1,p2,p3;
p1.age=30;
//...
}
3.19 指出下列程序中的錯誤,并說明為什么。
#include <iostream.h>
class Student{
int sno;
int age;
void printStu();
void setSno(int d);
};
void printStu()
{ cout<<"\nStudent No. is "<<sno<<".";
cout<<" age is "<<age<<"."<<endl;
}
void setSno(int s)
{ sno=s;
}
void SetAge(int a)
{ age=a;
}
void main()
{ Student lin;
lin.setSno(20021);
lin.setAge(20);
lin.printStu();
}
3.20 指出下列程序中的錯誤,并說明為什么。
#include <iostream.h>
class Point{
public:
int x,y;
private:
Point()
{ x=1;y=2;}
};
void main()
{ Point cpoint;
cpoint.x=2;
}
3.21 下面是一個計算器的定義,請完成該類成員函數的實現。
class counter{
public:
counter(int number);
void increment(); //給原值加1
void decrement(); //給原值減1
int getvalue(); //取得計數器值
void print(); //顯示計數
private:
int value;
};
3.22 根據注釋語句的提示,實現類Date的成員函數。
#include <iostream.h>
class Date{
public:
void printDate(); //顯示日期
void setDay(int d); //設置日的值
void setMonth(int m); //設置月的值
void setYear(int y); //設置年的值
private:
int day,month,year;
};
void main()
{ Date testDay;
testDay.setDay(5);
testDay.setMonth(10);
testDay.setYear(2003);
testDay.printDate();
}
3.23 建立類cylinder,cylnder的構造函數被傳遞了兩個double值,分別表示圓柱體的半徑和高度。用類cylinder計算圓柱體的體積,并存儲在一個double變量中。在類cylinder中包含一個成員函數vol(),用來顯示每個cylinder對象的體積。
3.24 構建一個類book,其中含有兩個私有數據成員qu和price,建立一個有5個元素的數組對象,將qu初始化為1~5,將price初始化為qu的10倍。顯示每個對象的qu*price值。
3.25 修改上題,通過對象指針訪問對象數組,使程序以相反的順序顯示對象數組的qu*price的值。
3.26 構建一個類Stock,含字符數組stockcode[]及整型數據成員quan、浮點型數據成員price。構造函數含3個參數:字符數組na[]及q、p。當定義Stock的類對象時,將對象的第1個字符串參數賦給數據成員stockcode,第2個和第3個參數分別賦給quan和price。未設置第2個和第3個參數時,quan的值為1000,price的值為8.98。成員函數print()使用this指針,顯示對象內容。
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -