酒鬼隨機漫步(一個矢量類)

摘要: 閱讀全文

這是一個定義的一個矢量類, 然后用矢量類模擬一個酒鬼的隨機漫步

問題很簡單, 實現也不麻煩, 但是這個小程序卻可以呈現出許多語法知識。而且代碼風格也不錯,因此保存在了這篇博客中。

?

建議:

?? ????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.pswp.cn/news/256637.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/256637.shtml
英文地址,請注明出處:http://en.pswp.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博客…