酒鬼随机漫步(一个矢量类)

摘要: 阅读全文

这是一个定义的一个矢量类, 然后用矢量类模拟一个酒鬼的随机漫步

问题很简单, 实现也不麻烦, 但是这个小程序却可以呈现出许多语法知识。而且代码风格也不错,因此保存在了这篇博客中。

 

建议:

       1. 类的声明以及函数的声明放到一个文件夹内, 并且在一些必要的地方加上注释!

   2. 函数的实现放到另一个文件内。

       3. 将程序要具体解决的问题放到另外的一个文件里。(详见代码!)

 

好处: 把类的接口和实现细节分离开, 易于更改某个函数的功能。

          把函数的声明和定义分开, 提高代码可读性。

          把类的声明和定义 与 要解决的问题分开, 提高,类的重用性!

 

                                         定义类(声明类内的函数)

// vect.h -- Vector class with <<, mode state
#ifndef VECTOR_H_
#define VECTOR_H_
#include <iostream>
namespace VECTOR
{class Vector{public:enum Mode{RECT, POL};// RECT for rectangular, POL for Polar modesprivate:double x;        // horizontal valuedouble y;        // vertical valuedouble mag;      // length of vector in degreesdouble ang;// direction of vector in degreesMode mode;  // private methods for setting valuesvoid set_mag();void set_ang();void set_x();void set_y();public:Vector();Vector(double n1, double n2, Mode form = RECT);void reset(double n1, double n2, Mode form = RECT);~Vector();double xval() const {return x; }        // report x valuedouble yval() const {return y; }        // report y valuedouble magval() const {return mag; }    // report magnitudedouble angval() const {return ang; }    // report anglevoid polar_mode();                      // set mode to POLvoid rect_mode();                       // set mode to RECT// operator overloadingVector operator+(const Vector & b) const;Vector operator-(const Vector & b) const;Vector operator-()const;Vector operator*(double n) const;// friendsfriend Vector operator*(double n, const Vector & a);friend std::ostream & operator<<(std::ostream & os, const Vector & v);};
}    // end namespace VECTOR
#endif

 上面代码涵盖了许多关于类的基础知识:  名称空间与作用域 ,  实现类内部常量的方法,  构造函数, 析构函数, 运算符重载, 友元函数, 关于多种实现方法等。

 

PS: 实现类内部常量的方法: (1)枚举类型。 (2) static const int  常量

        运算符重载: 注意操作数的顺序。

                                           

                                                           函数定义

// vect.cpp -- methods for the Vector class 
#include <cmath>
#include "vect.h"  // include <iostream>
using std::sqrt;
using std::sin;
using std::cos;
using std::atan;
using std::atan2;
using std::cout;namespace VECTOR
{// compute degree in one radianconst double Rad_to_deg = 45.0/atan(1.0);// should be about 57.2957795130823// private methods// calculate magnitude from x and yvoid Vector::set_mag(){mag = sqrt(x*x + y*y);}void Vector::set_ang(){if(x == 0.0&& y== 0.0)ang = 0.0;else ang = atan2(y, x);}//set x from polar coordinatevoid Vector::set_x(){x = mag*cos(ang);}//set y from polar coodinatevoid Vector::set_y(){y = mag * sin(ang);}// public methodsVector::Vector() // default constructor
    {x = y = mag = ang = 0.0;mode = RECT;}// construct vector from rectangular coordinates if form is r// (the default) or else from polar coordinates if form is pVector::Vector(double n1, double n2, Mode form){mode = form;if(form == RECT){x = n1;y = n2;set_mag();set_ang();}else if(form == POL){mag = n1;ang = n2/Rad_to_deg;set_x();set_y();}else{cout << "Incorrect 3rd argument to Vector() --";cout << "vector set to 0.0";mode = RECT;}}// reset vector from rectangular coodinates if form is// RECT (the default) or else form polar coordinates if// form is POLvoid Vector::reset(double n1, double n2, Mode form){mode = form;if(form == RECT){x = n1;y = n2;set_mag();set_ang();}else if (form == POL){mag = n1;ang = n2/Rad_to_deg;set_x();set_y();}else{cout << "Incorrect 3rd argument to Vector() -- ";cout <<"vector set to 0.0\n";x = y = mag = ang = 0.0;mode = RECT;}}Vector::~Vector() // destructor
    {}void Vector::polar_mode()  //set to polar mode
    {mode = POL;}void Vector::rect_mode()// set to rectangular mode
    {mode = RECT;}// operator overloading// add two VectorsVector Vector::operator+(const Vector & b) const{return Vector(x + b.x, y + b.y);}//subtract Vector b from a Vector Vector::operator-(const Vector & b) const{return Vector(x-b.x, y-b.y);}// reverse sign of VectorVector Vector::operator-() const{return Vector(-x, -y);}// multiply vector by nVector Vector::operator*(double n) const{return Vector(n*x, n*y);}// friend methods// multiply n by Vector aVector operator*(double n, const Vector & a){return a * n;}//display rectangular coordinates if mode is RECT// else display polar coordinates if mode is POLstd::ostream & operator<<(std::ostream & os, const Vector & v){if (v.mode == Vector::RECT)os << "(x,y) = (" << v.x << ", " << v.y << ")";else if (v.mode == Vector::POL){os << " (m,a) = (" << v.mag << ", "<< v.ang*Rad_to_deg << ")"; }elseos << "Vector object mode is invalid";return os;}
}  // end namespace VECTOR

 

 

                                                           具体解决的问题

// randwalk.cpp -- using the Vector class
// compile with the vect.cpp file
#include <iostream>
#include <cstdlib> // rand(), srand() pototypes
#include <ctime>   // time() pototype
#include "vect.h"int main()
{using namespace std;using VECTOR::Vector;srand(time(0));   // seed random-number generatordouble direction;Vector step;Vector result(0.0, 0.0);unsigned long steps = 0;double target;double dstep;cout << "Enter target distance (q to quit): ";while(cin >> target){cout << "Enter step length: ";if(!(cin>>dstep))break;while(result.magval() < target){direction = rand()%360;step.reset(dstep, direction, Vector::POL);result = result + step;steps++;}cout << "After " << steps <<" steps, the subject ""has the following location:\n";cout << result <<endl;result.polar_mode();cout << "or\n" << result << endl;cout << "Average outward distance per step = "<< result.magval()/steps << endl;steps = 0;result.reset(0.0, 0.0);cout << "Enter target distance (q to quit): ";}cout << "Bye!\n";cin.clear();while(cin.get() != '\n')continue;return 0;
}

 

二。一个简易的string类。

锻炼内容:

            拷贝构造函数(深拷贝与浅拷贝)

            重载赋值运算符(深赋值)

            许多的细节与技巧!

 

类的声明

//sting1.h -- fixed and augmented string class definition
#ifndef STRING1_H_
#define STRING1_H_
#include <iostream>
using std::ostream;
using std::istream;class String
{
private:char * str;                            // pointer ot stringint len;                            // length of stringstatic int num_strings;                // number of objectsstatic const int CINLIM = 80;        // cin input limit
public:// construction and other methodsString(const char * s);             // constructorString();                            // default constructorString(const String &);                // copy constructor~String();                            // destructor int length() const { return len; }// overloaded operator methodsString & operator=(const String &);String & operator=(const char *);char & operator[](int i);const char & operator[](int i)const;// overloaded operator friendsfriend bool operator<(const String &st, const String &st2);friend bool operator>(const String &st1, const String &st2);friend bool operator==(const String &st, const String &st2);friend ostream & operator<<(ostream & os, const String & st);friend istream & operator>>(istream & is, String & st);//static functionstatic int HowMany();
};
#endif
View Code

 

类方法的实现。

// string1.cpp -- String class methods
#include <cstring>                    // string.h for some
#include "string1.h"                // includes <iostream>
using std::cin;
using std::cout;// initializing static class member
int String::num_strings = 0;// static method
int String::HowMany()
{return num_strings;
}// class methods
String::String(const char * s)        // construct String from C string
{len = std::strlen(s);             // set sizestr = new char[len + 1];        // allot storagestd::strcpy(str, s);            // initialize pointernum_strings++;                     // set object count
}String::String()                    // default constructor
{len = 4;str = new char[1];str[0] = '\0';                    // default stringnum_strings++;
}String::String(const String & st)
{num_strings++;                     // handle static member updatelen = st.len;                    // same lengthstr = new char [len + 1];        // allot space std::strcpy(str, st.str);        // copy string to new location
}String::~String()                      // necesserary destructor
{--num_strings;                    // requireddelete [] str;                     // required
}// overloaded operator methods// assign a String to a String
String & String::operator=(const String & st)
{if(this == &st)return *this;delete [] str;len = st.len;str = new char[len + 1];std::strcpy(str, st.str);return *this;
}// assign a C string to a String
String & String::operator=(const char * s)
{delete [] str;len = std::strlen(s);str = new char[len + 1];std::strcpy(str, s);return *this;
}// read-write char access for non-const String
char & String::operator[](int i)
{return str[i];
}// read-only char access for const string
const char & String::operator[](int i) const
{return str[i];
}// averloaded operator friendsbool operator<(const String &st1, const String &st2)
{return (std::strcmp(st1.str, st2.str) < 0);
}bool operator>(const String &st1, const String &st2)
{return st2 < st1;
}bool operator==(const String &st1, const String &st2)
{return (std::strcmp(st1.str, st2.str)==0);
}// simple String output
ostream & operator<<(ostream & os, const String & st)
{os << st.str;return os;
}// quick and dirty String input
istream & operator>>(istream & is, String & st)
{char temp[String::CINLIM];is.get(temp, String::CINLIM);if(is)st = temp;while (is && is.get() != '\n')continue;return is;
}
View Code

 

main(), 测试String类。

// saying1.cpp -- using expanded String class 
// complile with string1.cpp
#include <iostream>
#include "string1.h"
const int MaxLen = 81;
int main()
{using std::cout;using std::cin;using std::endl;String name;cout << "Hi, what's your name?\n>> ";cin >> name;cout << name << ", please enter up to " << ArSize<< " short sayings <empty line to quit>:\n";String sayings[ArSize];         // array of objectschar temp[MaxLen]                // temporary string storageint i;for (i = 0; i < ArSize; i++){cout << i + 1 << ": ";cin.get(temp, MaxLen);while(cin && cin.get()!='\n')continue;if(!cin||temp[0] == '\0')    // empty line?break;                    // i not increamentedelsesayings[i] = temp;        // overloaded assignment
    }int total = i;                     // total # of lines readif( total > 0){cout << "Here are your sayings:\n";for (i = 0; i < total; i++)cout << sayings[i][0] << ": " << sayings[i] << endl;int shortest = 0;int first = 0;for(i = 1; i < total; i++){if(sayings[i].length() < sayings[shortest].length())shortest = i;if(sayings[i] < sayings[first])first = i;}cout << "Shortest saying:\n" << sayings[shortest] << endl;cout << "First alphabetically:\n" << sayings[first] << endl;cout << "This program used " << String::HowMany()<< " String objects. Bye.\n"}elsecout << "No input! Bye.\n";return 0;
}
View Code

 

 

代码源自: C++ Primer Plus  。 小恪亲自敲写!

感悟:  如果一部书经久不衰, 一定是有它的理由的! 正如这部书,  内容细致而深刻, 全面而严谨。获益良多!此书有点儿厚,与诸君共勉。

转载于:https://www.cnblogs.com/acm1314/p/4854000.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/256637.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

对高并发流量控制的一点思考

前言 在实际项目中&#xff0c;曾经遭遇过线上5WQPS的峰值&#xff0c;也在压测状态下经历过10WQPS的大流量请求&#xff0c;本篇博客的话题主要就是自己对高并发流量控制的一点思考。 应对大流量的一些思路 首先&#xff0c;我们来说一下什么是大流量&#xff1f; 大流量&…

ndk学习19: 使用Eclipse调试so

1. 设置调试选项在AndroidManifest文件加入允许调试android:debuggable"true" 此时编译项目会多出:2. 配置调试代码把需要调试的代码,放如按钮事件中,如果放在OnCreate会导致连接调试器时,代码已经跑完了Button btnTest (Button)findViewById(R.id.button1);btnT…

Inside the C++ Object Model | Outline

《Inside the C Object Model&#xff08;C对象模型&#xff09;》&#xff0c;这是一本灰常不错的书&#xff01; CSDN下载页面&#xff08;中文&#xff0c;侯捷译&#xff09; 豆瓣评论 读书笔记目录如下&#xff08;不定时更新&#xff09;&#xff1a; 转载于:https://www…

最优化课程笔记07——约束问题的非线性规划方法(重点:拉格朗日乘子法和惩罚函数法)

7.1 间接法&#xff1a;约束转化为无约束问题&#xff08;含一个重点&#xff1a;拉格朗日乘子法&#xff09; 当维数多的时候不适用 7.1.2拉格朗日乘子法&#xff08;重点&#xff09; 7.1.2.1 等式约束问题 7.1.2.2 不等式约束问题 7.1.3 惩罚函数法&#xff08;内惩罚函数法…

工业相机:传感器尺寸与像元尺寸的关系

相同分辨率的工业相机&#xff0c;传感器面积越大&#xff0c;则其单位像素的面积也越大&#xff0c;成像质量也会越好。同样的500万像素的工业相机&#xff0c;2/3”的传感器成像质量就要优于1/2”的。一般来说&#xff0c;工业相机的靶面大小&#xff0c;如果要求不是太严格&…

macOS下安装ipython

macOS下sudo安装ipython&#xff0c;会提示限错误&#xff1a; [Errno 1] Operation not permitted: /tmp/pip-Elrhse-uninstall/System/Library... 解决方法&#xff1a; pip install ipython --user -U 参考&#xff1a; http://chaishiwei.com/blog/994.html 本文转自 h2app…

结构化查询语言包含哪些方面?

结构化查询语言SQL&#xff08;STRUCTURED QUERY LANGUAGE&#xff09;是最重要的关系数据库操作语言&#xff0c;并且它的影响已经超出数据库领域&#xff0c;得到其他领域的重视和采用&#xff0c;如人工智能领域的数据检索&#xff0c;第四代软件开发工具中嵌入SQL的语言等。…

Opencv 找轮廓并画出相应的矩形

找轮廓参考以下大神的&#xff0c;对于里面的方法和结果存储解释的很清楚&#xff1b; http://blog.csdn.net/gubenpeiyuan/article/details/44922413 缺少的是画相应包围矩形的&#xff0c;其中找矩形用最小外接矩形函数cvMinAreaRect2 。 CvBox2D rect; CvPoint2D32f Corner…

C# 图片识别(支持21种语言)

图片识别的技术到几天已经很成熟了&#xff0c;只是相关的资料很少&#xff0c;为了方便在此汇总一下&#xff08;C#实现&#xff09;&#xff0c;方便需要的朋友查阅&#xff0c;也给自己做个记号。 图片识别的用途&#xff1a;很多人用它去破解网站的验证码&#xff0c;用于达…

搭建Git Server - Centos+Gitosis

参考并部分转载自&#xff1a;http://www.pfeng.org/archives/757 1. 安装依赖 yum -y install curl-devel expat-devel gettext-devel openssl-devel zlib-devel perl-devel git python python-setuptools2. 安装gitosis git clone git://github.com/res0nat0r/gitosis.git cd…

php中rsa加密及解密和签名及验签

加密的内容长度限制为密钥长度少11位,如128位的密钥最多加密的内容为117个长度。 公钥加密    $public_contentfile_get_contents(公钥路径);    $public_keyopenssl_get_publickey($public_content);        $original_str待加密的内容;    $original_arr…

Opencv ---像素坐标转世界坐标(已知外参)

只能求取已知外参的世界坐标平面上的世界坐标&#xff0c;具体公式如图片所示&#xff01; PS&#xff1a;字丑请谅解&#xff01;

最优化5-8章重点(考试点全)

10道题&#xff0c;每道题10分&#xff0c;5-8章大概4题左右&#xff0c;后面的章节主要考的是概念题

多对多关联映射(双向)

关联映射方面的最后一篇了&#xff0c;我觉得映射文件的编写是使用hibernate的基础&#xff0c;而关联映射又是基础的基础&#xff0c;所以这方面分的细一些&#xff0c;罗嗦一些&#xff0c;说明白就好&#xff0c;呵呵。多对多关联(双向)&#xff0c;相对单向&#xff0c;在实…

sort-排座椅

题目描述 Description上课的时候总有一些同学和前后左右的人交头接耳&#xff0c;这是令小学班主任十分头疼的一件事情。不过&#xff0c;班主任小雪发现了一些有趣的现象&#xff0c;当同学们的座次确定下来之后&#xff0c;只有有限的D对同学上课时会交头接耳。同学们在教室中…

JSONModel的基本使用

JSONModel 是一个库,它能智能并且快速的创建出数据 model,你可以在你的 iOS 项目或者 OSX 项目上使用它。 使用前准备 添加 JSONModel 到你的工程中 1、需要的环境: ARC,iOS 5.0 / OSX 10.7 引入框架SystemConfiguration.framework2、获取途径&#xff1a; 1&#xff09;、通过…

图像处理 伽玛校正

http://blog.csdn.net/lichengyu/article/details/20840135 本质上是关于灰度的一个幂函数&#xff0c;当系数gamma大于1时&#xff0c;低灰度值的动态范围减小&#xff0c;高灰度值的动态范围增大&#xff0c;整体的灰度值减小&#xff1b;gamma小于1时则相反&#xff1b; 人…

matlab常用工具箱的调用指令

转自:http://blog.sina.com.cn/s/blog_86186c970102va9g.html Matlab常用工具箱的调用命令 1. 优化工具箱​​ 用途:优化问题 调用命令:在Command Window输入“optimtool”​,其窗口如下 图1 Optimization Tool 2. 神经网络工具箱​ 用途:数据拟合、模式识别和分类…

tomcat起不来的问题已经解决

tomcat 起不来的问题:\apache-tomcat-6.0.10\bin 中startup.bat 起不来&#xff0c;一闪就没了。说明&#xff1a;环境变量没有配置好。解决办法&#xff1a;配置环境变量&#xff1a;JAVA_HOME C:\Program Files\Java\jdk1.6.0_03就可以解决问题了本文转自 yuwenhu 51CTO博客…