实验名称 | 类的定义和使用 |
实验目的 |
|
实验任务 |
11.1(第251页 修正版第257页) ex11_01 下列程序有几个错误,请修正,并运行,写出执行结果。 #include <iostream> #include <cmath> using namespace std; class point { public: void set(double ix,double iy) { x=ix; y=iy; } double xoffset() { return x; } double yoffset() { return y; } double angle() { return (180/3.14159)*atan2(y,x); } double radius() { return sqrt(x*x+y*y); } protected: double x; double y; } int main() { point p; double x,y; cout<<"Enter x and y:\n"; cin>>x>>y; p.set(x,y); p.x+=5; p.y+=6; cout<<"angle="<<p.angle() <<",radius="<<p.radius() <<",xoffset="<<p.xoffset() <<",yoffset="<<p.yoffset()<<endl; return 0; } 11.2(第252页 修正版第258页) ex11_02 将下列程序分离类定义和主函数,改成多文件结构。主函数使用类的方式采取包含类定义的头文件的方法。写出运行结果。 #include<iostream> using namespace std; 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() { cout<<"Meow.\n"; } int main() { Cat frisky; frisky.setAge(5) ; frisky.meow(); cout<<"frisky is a cat who is " <<frisky.getAge()<<" years old.\n"; frisky.meow(); return 0; } |
实验内容
#include<iostream> using namespace std; #include<cmath> class Point{ public: void Set(double ix,double iy) { x=ix; y=iy; } double xOFFset() { return x; } double yOFFset() { return y; } double angle() { return (180/3.14159)*atan2(y,x); } Double radius() { return sqrt(x*x+y*y); } protected: double x; double y; }; bool getInput(double& x,double &y) { cout <<"Enter x and y :\n"; cin >> x>> y; return x>=0; } int main() { Point p; for(double x,y;getInput(x,y);) { p.Set(x,y); cout <<"angle = "<< p.angle() <<" radius = "<<p.radius() <<" x offset = "<<p.xOFFset() <<" y offset = "<< p.yOFFset()<< endl; } return 0; }
#include <iostream> #include <cmath> using namespace std; class point { public: void set(double ix,double iy) { x=ix; y=iy; } double xoffset() { return x; } double yoffset() { return y; } double angle() { return (180/3.14159)*atan2(y,x); } double radius() { return sqrt(x*x+y*y); } double& setx() { return x; } double& sety() { return y; } protected: double x; double y; }; int main() { point p; double x,y; cout<<"Enter x and y:\n"; cin>>x>>y; p.set(x,y); p.setx()+=5; p.setx()+=6; cout<<"angle="<<p.angle() <<",radius="<<p.radius() <<",xoffset="<<p.xoffset() <<",yoffset="<<p.yoffset()<<endl; return 0; }
#include"Cat.h" int main() { Cat frisky; frisky.setAge(5) ; frisky.meow(); cout<<"frisky is a cat who is " <<frisky.getAge()<<" years old.\n"; frisky.meow(); return 0; } #include<iostream> using namespace std; 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() { cout<<"Meow.\n"; } | |
小结 |
c++高级程序设计语言实验九类的定义和使用
最新推荐文章于 2024-10-02 08:00:00 发布
该文提供了关于C++中类和对象的实践操作,包括Point类的定义和使用,涉及成员函数的设置、调用,以及错误程序的修正。实验要求将代码整合到单个源文件中,并通过输入坐标来计算角度和半径。此外,还展示了如何将类定义与主函数分离,构建多文件项目结构。
摘要由CSDN通过智能技术生成