C++程序设计(第二版)钱能-第8章--类 下载本文

内容发布更新时间 : 2024/5/2 3:07:35星期一 下面是文章的全部内容请认真阅读。

第8章 类

8.9 练习8(Exercises 8)

1.下面程序错在哪里?

//===================================== //e0801.cpp //找错

//===================================== #include

using namespace std;

//------------------------------------- class Point{ protected:

double x; //x轴分量 double y; //y轴分量 public:

void Set(double ix, double iy){ //设置坐标 x = ix; y = iy;

}//--------------------------------

double xOffset(){ //取x轴坐标分量 return x;

}//--------------------------------

double yOffset(){ //取y轴坐标分量 return y;

}//-------------------------------- double angle(){ //取点的极坐标0 return (180/3.14159)*atan2(y,x); }//--------------------------------

double radius(){ //取点的极坐标半径 return sqrt(x*x+y*y); }

};//----------------------------------- int main() {

Point p; double x,y;

cout << \ cin >> x >> y;

p.Set(x,y); p.x+=5; p.y+=6;

cout << \ << \ << \

<< \}//===================================== 解答:

程序缺少头文件iostream,类Point定义结束时,最后应该加上半角分号表示语句的结束。

2.将下面程序分离类定义、类的实现和main函数,实现多文件程序结构: //===================================== //e0802.cpp //使用Cat类

//===================================== #include

//------------------------------------- class Cat{ int itsAge; public:

int getAge();

void setAge(int age);

void meow(); //喵喵叫

};//----------------------------------- int Cat::getAge(){ return itsAge; }

void Cat::setAge(int age){ itsAge = age; } void Cat::meow(){ std::cout << \//------------------------------------- int main() {

Cat frisky;

frisky.setAge(5); frisky.meow();

std::cout << \old.\\n\

frisky.meow();

}//==================================== 解答: File1

//===================================== //main函数

//===================================== #include

#include \

#include \int main() {

Cat frisky;

frisky.setAge(5); frisky.meow();

std::cout << \old.\\n\

frisky.meow();

}//==================================== File2

//===================================== //Cat类定义

//===================================== class Cat{ int itsAge; public:

int getAge();

void setAge(int age);

void meow(); //喵喵叫

};//----------------------------------- File3

//===================================== //Cat类的实现

//===================================== int Cat::getAge(){ return itsAge; }

void Cat::setAge(int age){ itsAge = age; } void Cat::meow(){ std::cout << \

3.定义一个满足如下要求的Date类: (1)用月/日/年的格式输出日期; (2)可运行在日期上加一天操作; (3)设置日期操作。 解答:

#include using namespace std; class Date {

private: int day; int month; int year;

bool IsLeapYear(); // 输入日期格式涉及到对闰年的判断 public: