1. 程式人生 > >【實驗5】類與對象3

【實驗5】類與對象3

叠代器 代碼 getline 。。 頭文件 ... 交換 使用 希望

1、實驗內容1

#include <iostream>
#include <vector>
#include <string>
using namespace std;

// 函數聲明 
void output1(vector<string> &);  
void output2(vector<string> &);  

int main()
{
    vector<string>likes, dislikes; // 創建vector<string>對象likes和dislikes
    
    
// 為vector<string>數組對象likes添加元素值 ( favorite book, music, film, paintings,anime,sport,sportsman,etc) // 補足代碼 // 。。。 likes.push_back("ONER"); likes.push_back("katto"); likes.push_back("pinkray"); likes.push_back("BC221"); cout << "-----I like these-----" << endl;
// 調用子函數輸出vector<string>數組對象likes的元素值 // 補足代碼 // 。。。 output1(likes); // 為vector<string>數組對象dislikes添加元素值 // 補足代碼 // 。。。 dislikes.push_back("english"); dislikes.push_back("coriander"); dislikes.push_back("chocolate"); dislikes.push_back("sit-up"); cout
<< "-----I dislike these-----" << endl; // 調用子函數輸出vector<string>數組對象dislikes的元素值 // 補足代碼 // 。。。 output1(dislikes); // 交換vector<string>對象likes和dislikes的元素值 // 補足代碼 // 。。。 likes.swap(dislikes); cout << "-----I likes these-----" << endl; // 調用子函數輸出vector<string>數組對象likes的元素值 // 補足代碼 // 。。。 output2(likes); cout << "-----I dislikes these-----" << endl; // 調用子函數輸出vector<string>數組對象dislikes的元素值 // 補足代碼 // 。。。 output2(dislikes); return 0; } // 函數實現 // 以下標方式輸出vector<string>數組對象v的元素值 void output1(vector<string> &v) { // 補足程序 // 。。。 for(int i=0;i<v.size();++i) cout << v[i] << " "; cout << endl; } // 函數實現 // 以叠代器方式輸出vector<string>數組對象v的元素值 void output2(vector<string> &v) { // 補足程序 // 。。。 vector<string>::iterator it; for(it = v.begin();it != v.end();++it) cout << *it << " " ; cout << endl; }

截圖:

技術分享圖片

2、實驗內容2

6-17:

//指針p沒有賦初值,這樣的話會指向一個不確定地址,很危險。所以要為指針p賦初值,定義一個int型變量a初始化指針p。
//修改後的代碼如下:
#include<iostream>
using namespace std;
int main(){
    int a; 
    int *p = &a;
    *p = 9;
    cout << "The value at p:" << *p;
    return 0; 
} 
//遇到的問題:第一次我想把指針p初始化為空指針int *p=NULL,發現還是無法運行。所以定義了另外一個變量。

6-18:

//代碼中用new申請了堆空間用於存放一個int型數據,但是最後沒有釋放掉。我一開始加入了delete,但是發現報錯,於是在定義a時就把a定義成指針a,int*型函數返回p,最後用delete釋放內存。
//改正後:
#include<iostream>
using namespace std;
int* fn1(){
    int *p = new int (5);
    return p;
}
int main(){
    int *a = fn1();
    cout << "the value of a is :" << *a;
    delete a;
    return 0; 
} 

3、實驗內容3:

//main.cpp
#include <iostream>
#include "matrix.h"
using namespace std; 
int main() {
    int l,c;
    int i,j;
    int n;
    float M[l*c];
    cout << "輸入矩陣行數和列數:" ;
    cin >> l >> c; 
    cout<<"輸入矩陣:"<<endl; 
    for( i = 0 ; i < l*c ; i++ )
    cin >> M[i] ;
    Matrix m(l,c);
    m.setMatrix(M);
    cout << "輸出矩陣:" << endl;
    m.printMatrix();
    cout << "輸入i和j然後返回在第i行第j列的數:"  ;
    cin >> i >> j;
    cout << m.element(i,j) << endl;
    cout << "你希望重新設置這個數為:" ;
    cin >> n; 
    m.setElement (i,j,n);
    cout << "現在這個數為:"  ;
    cout << m.element(i,j) << endl;
    cout << "矩陣的行數與列數為:"  ;
    cout << m.getLines() << " " << m.getCols() << endl ;
    return 0;
}

//matrix.cpp
#include <iostream>
#include "matrix.h"
using namespace std;
int i,j;
//構造函數
Matrix::Matrix(int n):lines(n),cols(n){
    p = new float[lines*cols];
}

//構造函數重載 
Matrix::Matrix(int n, int m):lines(n),cols(m){
    p = new float[lines*cols];
} 

//復制構造函數
Matrix::Matrix(const Matrix &X):lines(X.lines),cols(X.cols){
    p = new float[lines*cols];
    for(i = 0;i < lines*cols;i++)
    p[i] = X.p[i];
}

//析構函數 釋放空間 
Matrix::~Matrix(){
    delete[] p;
}

// 矩陣賦初值,用pvalue指向的內存塊數據為矩陣賦值 
void Matrix::setMatrix(const float *pvalue){
    for(i = 0;i < lines*cols;i++)
    p[i] = pvalue[i];
}

// 顯示矩陣
void Matrix::printMatrix() const{
    for(i = 0;i < lines;i++){
        for(j = 0;j < cols;j++)
            cout << p[i*lines+j] << " ";
        cout<<endl;
    }
}

//設置矩陣第i行第j列元素值為value        
void Matrix::setElement(int i, int j, int value){
    p[(i -1)*cols + j - 1]= value;
}
//matrix.h
#ifndef MATRIX_H
#define MATRIX_H
class Matrix {
    public:
        Matrix(int n); // 構造函數,構造一個n*n的矩陣 
        Matrix(int n, int m); // 構造函數,構造一個n*m的矩陣 
        Matrix(const Matrix &X); // 復制構造函數,使用已有的矩陣X構造 
        ~Matrix(); //析構函數 
        void setMatrix(const float *pvalue); // 矩陣賦初值,用pvalue指向的內存塊數據為矩陣賦值 
        void printMatrix() const; // 顯示矩陣
        inline float &element(int i, int j)//返回矩陣第i行第j列元素的引用
        {
            return *(p + (i - 1)*cols + j - 1);
        }
        inline float element(int i, int j) const// 返回矩陣第i行第j列元素的值 
        {
            return p[(i - 1)*cols + j - 1];
        }
        void setElement(int i, int j, int value); //設置矩陣第i行第j列元素值為value
        inline int getLines() const //返回矩陣行數 
        {
            return lines;
        }
        inline int getCols() const //返回矩陣列數 
        {
            return cols;
        }
    private:
        int lines;    // 矩陣行數
        int cols;      // 矩陣列數 
        float *p;   // 指向存放矩陣數據的內存塊的首地址 
};
#endif

運行截圖:

技術分享圖片

輸出函數有問題,我試著走了一遍的確有問題但是想不出解決方法……

過程中出現的問題:

1、函數中的p[(i-1)*lines + (j-1)]= value;我原本寫了p+(i-1)*lines + (j-1)= value; 報錯說賦值左邊是變量不能是表達式。

2、中途有一次getLinsgetCols函數報錯說不能有cv限定,百度了一下也沒怎麽懂什麽是cv限定……

4、實驗內容4

冷靜下來寫一下感覺其實很簡單……但是考試的時候就很慌腦子一片空白……

第一題:

用時間做種子來實現隨機數,一開始忘了加時間有關的頭文件後來加上了。在類定義中加入了your_number實現輸入自己的學號。循環500次隨機,每抽到一次就把計數用的count1,最後用count除以次數500得到一個概率值,輸出。

//1
#include<iostream>
#include<cstdlib> 
#include<ctime>
using namespace std;

class Dice{          //Dice類定義 
    public:
        Dice(int n,int a);
        int cast();
    private:
        int sides;
        int your_number; 
};


//構造函數 
Dice::Dice(int n,int a):sides(n),your_number(a){ }
int Dice::cast(){
    srand(time(NULL));
    int ra; //計數 
    for(int i = 0; i<500 ;i++){
        if(rand()%sides+1==your_number)
        ++ra;
    }
    return ra;
}

int main(){
    int nu,your_number;
    cout << "Please enter the number of the class:" ;
    cin >> nu;
    cout <<"Please enter your number in the class:";
    cin >> your_number; 
    Dice p1(nu,your_number);
    cout << "result : " << (float)p1.cast()/500 <<endl;
    return 0;
} 

運行截圖:

技術分享圖片

第二題:

//User.h

#ifndef USER_H
#define USER_H
#include<string>

using namespace std;

class User{
    public:
        User(string na,string pa = "111111");
        void printUser();
        void printCurrentID();
        void changePassword();
        int static getCurrentID();
    private:
        int id;
        string name;
        string password;
        static int CurrentID;
        
}; 

#endif

//User.cpp

#include"User.h"
#include<iostream>
#include<string>

using namespace std;

int User::CurrentID=999;

User::User(string na,string pa):name(na),password(pa){
     CurrentID++;
     id = CurrentID;
}

void User::printUser(){
    cout << "ID:" << id << endl; 
    cout << "Name:" << name << endl;
    cout << "Password:" << password << endl;
}

void User::printCurrentID(){
    cout << CurrentID << endl;
    cout << "ID:" << id << endl; 
    cout << "Name:" << name << endl;
    cout << "Password:" << password << endl;
}

void User::changePassword(){
    string OldPassword,NewPassword;
    bool n = true;
    cout << "請輸入原密碼:" ;
    while(n){
        cin >> OldPassword;
        if (OldPassword != password)
            cout << "密碼錯誤!請重新輸入:";
        else
            n = false; 
    }
    n = true;
    cout << "請輸入新密碼:";
    while(n){
        cin >> NewPassword;
        if(NewPassword == OldPassword)
            cout << "新密碼不能和原密碼相同!請重新輸入新密碼:" ;
        else
            n = false; 
    }
    cout << "修改成功!" ; 
    password = NewPassword; 
}

int User::getCurrentID(){
    return CurrentID;
}
//main.cpp

#include <iostream>
#include"User.h"
#include <string>
using namespace std;
int main() {
    string na,pa;
    cout << "請輸入用戶名:" ;
    cin >> na;
    cout << "請輸入密碼:" ;
    cin >> pa;
    User u(na,pa);
    u.printUser();
    u.printCurrentID();
    u.changePassword();
    cout << "當前ID:" << u.getCurrentID() << endl;
    return 0;
}

運行截圖:

技術分享圖片

出現的問題:

1、定義構造函數時出現了兩次不同的初始化導致報錯。之後我在類的定義密碼初始化成111111,在構造函數的定義中把密碼再次初始化就ok了。

2、在重新設置密碼那邊,輸入原密碼判斷是否需要重新輸入時,我把輸入寫在了while循環外面導致瘋狂輸出“密碼錯誤!請重新輸入:”,然後把輸入寫到while循環裏面就好了。

第三題:

//book.h

#ifndef BOOK_H
#define BOOK_H

#include <string>
using std::string;

class Book {
    public:
        Book(string isbnX, string titleX, float priceX);  //構造函數  
        void print(); // 打印圖書信息 
    private:
        string isbn;
        string title;
        float price;
};
#endif

//book.cpp

#include "book.h"
#include <iostream> 
#include <string>
using namespace std;

// 構造函數
// 補足程序 
// ...
Book::Book(string isbnX, string titleX, float priceX):isbn(isbnX),title(titleX),price(priceX){
}


// 打印圖書信息
// 補足程序 
// ...
void Book::print() {
    cout<< "isbn : " << isbn <<endl;
    cout <<"title : " << title <<endl;
    cout <<"price : " << price <<endl;
}
//main.cpp

#include "book.h"
#include <vector>
#include <iostream>
using namespace std;

int main()
{
    // 定義一個vector<Book>類對象
    // 補足程序
    // ... 
    vector<Book>books;
     
    string isbn, title;
    float price;
    
    // 錄入圖書信息,構造圖書對象,並添加到前面定義的vector<Book>類對象中
    // 循環錄入,直到按下Ctrl+Z時為止 (也可以自行定義錄入結束方式) 
    // 補足程序
    // ... 
    cout << "請錄入圖書信息(按下Ctrl+Z停止錄入):" << endl; 
    int number;
    while(cin >> isbn >> title >> price){
        Book book(isbn,title,price);
        books.push_back(book);
        number++;
    }
    
    
    // 輸出入庫所有圖書信息
    // 補足程序
    // ... 
    cout << "當前所有圖書信息:" << endl;
    for (int n = 0; n < number ; n++)
        books[n].print();
    
    return 0;
}

運行截圖:

技術分享圖片

出現的問題:

這道題就是不太懂怎麽ctrl+Z結束,後來百度了發現原來本來就有這個功能……

【實驗5】類與對象3