首页 > 其他分享 >实验3 类与对象

实验3 类与对象

时间:2024-11-10 18:46:06浏览次数:1  
标签:std const cout 对象 int 实验 include string

实验任务1:

botton.hpp代码:

 1 #pragma once
 2 
 3 #include <iostream>
 4 #include <string>
 5 
 6 using std::string;
 7 using std::cout;
 8 
 9 // 按钮类
10 class Button {
11 public:
12     Button(const string &text);
13     string get_label() const;
14     void click();
15 
16 private:
17     string label;
18 };
19 
20 Button::Button(const string &text): label{text} {
21 }
22 
23 inline string Button::get_label() const {
24     return label;
25 }
26 
27 void Button::click() {
28     cout << "Button '" << label << "' clicked\n";
29 }
View Code

window.hpp代码:

 1 #pragma once
 2 #include "button.hpp"
 3 #include <vector>
 4 #include <iostream>
 5 
 6 using std::vector;
 7 using std::cout;
 8 using std::endl;
 9 
10 // 窗口类
11 class Window{
12 public:
13     Window(const string &win_title);
14     void display() const;
15     void close();
16     void add_button(const string &label);
17 
18 private:
19     string title;
20     vector<Button> buttons;
21 };
22 
23 Window::Window(const string &win_title): title{win_title} {
24     buttons.push_back(Button("close"));
25 }
26 
27 inline void Window::display() const {
28     string s(40, '*');
29 
30     cout << s << endl;
31     cout << "window title: " << title << endl;
32     cout << "It has " << buttons.size() << " buttons: " << endl;
33     for(const auto &i: buttons)
34         cout << i.get_label() << " button" << endl;
35     cout << s << endl;
36 }
37 
38 void Window::close() {
39     cout << "close window '" << title << "'" << endl;
40     buttons.at(0).click();
41 }
42 
43 void Window::add_button(const string &label) {
44     buttons.push_back(Button(label));
45 }
View Code

task1.cpp代码:

 1 #include "window.hpp"
 2 #include <iostream>
 3 
 4 using std::cout;
 5 using std::cin;
 6 
 7 void test() {
 8     Window w1("new window");
 9     w1.add_button("maximize");
10     w1.display();
11     w1.close();
12 }
13 
14 int main() {
15     cout << "用组合类模拟简单GUI:\n";
16     test();
17 }
View Code

运行结果截图:

 问题1:

自定义了两个类Botton 类和Window类

标准库类:使用iostream类、string类、vector类

Button类代表一个按钮,具有显示标签和点击的功能;Window类代表一个窗口,可以包含多个按钮,Window类中包含Button类的对象,用于表示窗口中的按钮。

 

问题2:

构造函数不需要 const,因为构造函数会修改对象的状态,初始化成员变量和添加初始按钮。不需要 inline,构造函数通常不适合内联。

click() display() close() add_button不需要 const,函数会输出信息并触发其他状态变化。不需要 inline,函数包含 I/O 操作和容器访问,不适合内联。

 

问题3:

调用window中的成员函数display时,通过字符串s显示四十个'*'分割界面。

 

实验任务2:

test2代码:

 1 #include <iostream>
 2 #include <vector>
 3 
 4 using namespace std;
 5 
 6 void output1(const vector<int> &v) {
 7     for(auto &i: v)
 8         cout << i << ", ";
 9     cout << "\b\b \n";
10 }
11 
12 void output2(const vector<vector<int>> v) {
13     for(auto &i: v) {
14         for(auto &j: i)
15             cout << j << ", ";
16         cout << "\b\b \n";
17     }
18 }
19 
20 void test1() {
21     vector<int> v1(5, 42);
22     const vector<int> v2(v1);
23 
24     v1.at(0) = -999;
25     cout << "v1: ";  output1(v1);
26     cout << "v2: ";  output1(v2);
27     cout << "v1.at(0) = " << v1.at(0) << endl;
28     cout << "v2.at(0) = " << v2.at(0) << endl;
29 }
30 
31 void test2() {
32     vector<vector<int>> v1{{1, 2, 3}, {4, 5, 6, 7}};
33     const vector<vector<int>> v2(v1);
34 
35     v1.at(0).push_back(-999);
36     cout << "v1: \n";  output2(v1);
37     cout << "v2: \n";  output2(v2);
38 
39     vector<int> t1 = v1.at(0);
40     cout << t1.at(t1.size()-1) << endl;
41     
42     const vector<int> t2 = v2.at(0);
43     cout << t2.at(t2.size()-1) << endl;
44 }
45 
46 int main() {
47     cout << "测试1:\n";
48     test1();
49 
50     cout << "\n测试2:\n";
51     test2();
52 }
View Code

运行截图:

 

问题1:

 vector<int> 类型的向量 v1,并用值 42 初始化了它的5个元素。

常量向量 v2,它是 v1 的拷贝。由于 v2 是常量,其内容不可修改。

修改 v1 的第一个元素为 -999。

 

问题2:

vector 类型的向量 v1,并初始化为包含两个子向量的向量。

常量向量 v2,它是 v1 的拷贝。由于 v2 是常量,所以不可修改。

向 v1 的第一个子向量添加元素 -999。

 

问题3:

获取v1里的第一个子向量赋值给t1

输出t1的最后一个元素-999,验证-999已经被添加

获取v2里的第一个子向量赋值给t2

输出t2的最后一个元素3

 

问题4:

标准库模板类vector的复制函数使用深复制,不需要至少提供一个const成员函数作为接口。

 

实验任务3:

task3代码:

 1 #include "vectorInt.hpp"
 2 #include <iostream>
 3 
 4 using std::cin;
 5 using std::cout;
 6 
 7 void output(const vectorInt &vi) {
 8     for(auto i = 0; i < vi.get_size(); ++i)
 9         cout << vi.at(i) << ", ";
10     cout << "\b\b \n";
11 }
12 
13 
14 void test1() {
15     int n;
16     cout << "Enter n: ";
17     cin >> n;
18 
19     vectorInt x1(n);
20     for(auto i = 0; i < n; ++i)
21         x1.at(i) = i*i;
22     cout << "x1: ";  output(x1);
23 
24     vectorInt x2(n, 42);
25     vectorInt x3(x2);
26     x2.at(0) = -999;
27     cout << "x2: ";  output(x2);
28     cout << "x3: ";  output(x3);
29 }
30 
31 void test2() {
32     const vectorInt  x(5, 42);
33     vectorInt y(10, 0);
34 
35     cout << "y: ";  output(y);
36     y.assign(x);
37     cout << "y: ";  output(y);
38     
39     cout << "x.at(0) = " << x.at(0) << endl;
40     cout << "y.at(0) = " << y.at(0) << endl;
41 }
42 
43 int main() {
44     cout << "测试1: \n";
45     test1();
46 
47     cout << "\n测试2: \n";
48     test2();
49 }
View Code

运行截图:

问题1:

深复制


问题2:

不能正常运行,返回值类型是常数且不可以被修改

会存在安全隐患,可以通过返回值修改数据,破坏函数的封装性和数据的完整性。

 

问题3:
 可以,但会存在额外的内存开销,因为存在复制。

 

实验任务4:

matrix.cpp代码:

 1 #pragma once
 2 
 3 #include <iostream>
 4 #include <cassert>
 5 
 6 using std::cout;
 7 using std::endl;
 8 
 9 // 类Matrix的声明
10 class Matrix {
11 public:
12     Matrix(int n, int m);           // 构造函数,构造一个n*m的矩阵, 初始值为value
13     Matrix(int n);                  // 构造函数,构造一个n*n的矩阵, 初始值为value
14     Matrix(const Matrix &x);        // 复制构造函数, 使用已有的矩阵X构造
15     ~Matrix();
16 
17     void set(const double *pvalue);         // 用pvalue指向的连续内存块数据按行为矩阵赋值
18     void clear();                           // 把矩阵对象的值置0
19     
20     const double& at(int i, int j) const;   // 返回矩阵对象索引(i,j)的元素const引用
21     double& at(int i, int j);               // 返回矩阵对象索引(i,j)的元素引用
22     
23     int get_lines() const;                  // 返回矩阵对象行数
24     int get_cols() const;                   // 返回矩阵对象列数
25 
26     void display() const;                    // 按行显示矩阵对象元素值
27 
28 private:
29     int lines;      // 矩阵对象内元素行数
30     int cols;       // 矩阵对象内元素列数
31     double *ptr;
32 };
33  
34 // 类Matrix的实现:待补足
35 Matrix::Matrix(int n,int m):lines(n),cols(m),ptr(new double[n*m]()){}
36  
37  Matrix::Matrix(int n):lines(n),cols(n),ptr(new double[n*n]()){}
38  
39  Matrix::Matrix(const Matrix &x):lines(x.lines),cols(x.cols),ptr(new double[lines*cols]()){
40      for(int i=0;i<lines*cols;i++)
41      ptr[i]=x.ptr[i];
42  }
43  
44  Matrix::~Matrix(){
45      delete[] ptr;
46  }
47  
48  void Matrix::set(const double *pvalue){
49      for(int i=0;i<lines*cols;i++)
50      ptr[i]=pvalue[i];
51  }
52  
53  void Matrix::clear(){
54      for(int i=0;i<lines*cols;i++)
55      ptr[i]=0.0;
56  }
57  
58  const double& Matrix::at(int i,int j) const
59  {
60      assert(i>=0&&i<lines&&j>=0&&j<cols);
61      return ptr[i*cols+j];
62  }
63  
64  double &Matrix::at(int i,int j)
65  {
66      assert(i>=0&&i<lines&&j>=0&&j<cols);
67      return ptr[i*cols+j];
68  }
69  
70  int Matrix::get_lines() const{
71      return lines;
72  }
73  
74  int Matrix::get_cols() const{
75      return cols;
76  }
77  
78  void Matrix::display() const{
79       for(int i=0;i<lines;i++){
80          for(int j=0;j<cols;j++){
81             cout<<at(i,j)<<" ";
82         }
83         cout<<endl;
84     }
85  }
86 Matrix.hpp
View Code

tesk4代码:

 1 #include "matrix.hpp"
 2 #include <iostream>
 3 #include <cassert>
 4 
 5 using std::cin;
 6 using std::cout;
 7 using std::endl;
 8 
 9 
10 const int N = 1000;
11 
12 // 输出矩阵对象索引为index所在行的所有元素
13 void output(const Matrix &m, int index) {
14     assert(index >= 0 && index < m.get_lines());
15 
16     for(auto j = 0; j < m.get_cols(); ++j)
17         cout << m.at(index, j) << ", ";
18     cout << "\b\b \n";
19 }
20 
21 
22 void test1() {
23     double x[1000] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
24 
25     int n, m;
26     cout << "Enter n and m: ";
27     cin >> n >> m;
28 
29     Matrix m1(n, m);    // 创建矩阵对象m1, 大小n×m
30     m1.set(x);          // 用一维数组x的值按行为矩阵m1赋值
31 
32     Matrix m2(m, n);    // 创建矩阵对象m1, 大小m×n
33     m2.set(x);          // 用一维数组x的值按行为矩阵m1赋值
34 
35     Matrix m3(2);       // 创建一个2×2矩阵对象
36     m3.set(x);          // 用一维数组x的值按行为矩阵m4赋值
37 
38     cout << "矩阵对象m1: \n";   m1.display();  cout << endl;
39     cout << "矩阵对象m2: \n";   m2.display();  cout << endl;
40     cout << "矩阵对象m3: \n";   m3.display();  cout << endl;
41 }
42 
43 void test2() {
44     Matrix m1(2, 3);
45     m1.clear();
46     
47     const Matrix m2(m1);
48     m1.at(0, 0) = -999;
49 
50     cout << "m1.at(0, 0) = " << m1.at(0, 0) << endl;
51     cout << "m2.at(0, 0) = " << m2.at(0, 0) << endl;
52     cout << "矩阵对象m1第0行: "; output(m1, 0);
53     cout << "矩阵对象m2第0行: "; output(m2, 0);
54 }
55 
56 int main() {
57     cout << "测试1: \n";
58     test1();
59 
60     cout << "测试2: \n";
61     test2();
62 }
View Code

运行截图:

 

实验任务5:

user.cpp代码:

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 class User{
 4     private:
 5         string name;
 6         string password;
 7         string email;
 8 
 9     public:
10         User(const string &name,const string &password="123456", const string &email=""):name(name),password(password),email(email){}
11     void set_email(){
12         string _email;
13         int tag=0;
14         cout<<"Enter email address: ";
15         while(tag==0){
16             cin>>_email;
17             int len=sizeof(_email);
18             for(int i=0;i<len;i++){
19                 if(_email[i]=='@')
20                   tag=1;
21             }
22             if(tag)
23                 cout<< "email is set successfully..."<<endl;
24             else
25                 cout<<"illegal email. Please re-enter email:";
26         }
27 
28     }
29 
30     void change_password(){
31         int attempt=3;
32         string old_password , new_password;
33         cout<<"Enter old password: ";
34         while(attempt>0){
35             attempt--;
36             cin>>old_password;
37             if(old_password==password){
38                 cout<<"Enter new password: ";
39                 cin>>new_password;
40                 password=new_password;
41                 cout<<"new password is set successfully..."<<endl;
42                 return ;
43             }
44             else{
45                 cout<<"password input error. Please re-enter again: ";
46             }
47         }
48         cout<<"password input error. Please try after a while. "<<endl;
49     }
50 
51     void display() const {
52         cout<<"name:   "<<name<<endl;
53         cout<<"pass:   ";
54         int length=sizeof(password);
55         for(int i=1;i<=length;i++)
56           cout<<"*";
57         cout<<endl;
58         cout<<"email:   "<<email<<endl;
59     }
60 };
View Code

tesk5:

 1 #include "user.hpp"
 2 #include <iostream>
 3 #include <vector>
 4 #include <string>
 5 
 6 using std::cin;
 7 using std::cout;
 8 using std::endl;
 9 using std::vector;
10 using std::string;
11 
12 void test() {
13     vector<User> user_lst;
14 
15     User u1("Alice", "2024113", "[email protected]");
16     user_lst.push_back(u1);
17     cout << endl;
18 
19     User u2("Bob");
20     u2.set_email();
21     u2.change_password();
22     user_lst.push_back(u2);
23     cout << endl;
24 
25     User u3("Hellen");
26     u3.set_email();
27     u3.change_password();
28     user_lst.push_back(u3);
29     cout << endl;
30 
31     cout << "There are " << user_lst.size() << " users. they are: " << endl;
32     for(auto &i: user_lst) {
33         i.display();
34         cout << endl;
35     }
36 }
37 
38 int main() {
39     test();
40 }
View Code

运行结果截图:

 

实验任务6:

 data.h代码:

 1 #pragma once
 2  class Date{        
 3  private:
 4     int year;        
 5     int month;        
 6     int day;    
 7     int totalDays;
 8   public:    
 9       Date(int year, int month, int day) ;
10      int getYear() const {return year;}
11      int getMonth() const {return month;}
12      int getDay() const {return day;}
13      int getMaxDay() const;     
14      bool isLeapYear() const {
15          return year%4==0 &&year%100 !=0 || year%400==0;
16      }
17  void show() const;
18  int distance(const Date& date) const {
19  return totalDays-date.totalDays;
20  }
21  }; 
22 date.h
View Code

 

data.cpp代码:

#include "date.h"
#include <iostream>
#include <cstdlib>
using namespace std;
namespace {
    const int DAYS_BEFORE_MONTH[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
}
Date::Date(int year, int month, int day) : year(year), month(month), day(day) {
    if (day <= 0 || day > getMaxDay()) {
        cout << "Invalid date:";
        show();
        cout << endl;
        exit(1);
    }
    int years = year - 1;
    totalDays = years * 365 + years / 4 - years / 100 + years / 400 + DAYS_BEFORE_MONTH[month - 1] + day;
    if (isLeapYear() && month > 2) 
    totalDays++;
}
int Date::getMaxDay()const {
    if (isLeapYear() && month == 2)
        return 29;
    else
        return DAYS_BEFORE_MONTH[month] - DAYS_BEFORE_MONTH[month - 1];
}
void Date::show() const {
    cout << getYear() << " - " << getMonth() << " - " << getDay();
}
View Code

accout.h代码:

 1 #ifndef __ACCOUNT_H__
 2 #define __ACCOUNT_H__
 3 #include "date.h"
 4 #include <string>
 5 class SavingsAccount {
 6 
 7     private:
 8         std::string id;
 9         double balance,rate,accumulation;
10         Date lastDate;
11         static double total;
12 
13         void record(const Date& date, double amount, const std::string& desc);
14 
15         void error(const std::string& msg) const;
16 
17         double accumulate(const Date& date) const {
18             return accumulation + balance * date.distance(lastDate);
19         }
20     public:
21         SavingsAccount(const Date& date, const std::string& id, double rate);
22         const std::string& getId() const {
23             return id;
24         }
25         double getBalance() const {
26             return balance;
27         }
28         double getRate() const {
29             return rate;
30         }
31         static double getTotal() {
32             return total;
33         }
34 
35         void deposit(const Date& date, double amount, const std::string& desc);
36 
37         void withdraw(const Date& date, double amount, const std::string& desc);
38 
39         void settle(const Date& date);
40 
41         void show() const;
42 };
43 #endif
View Code

accout.cpp代码:

 1 #include "account.h"
 2 #include <cmath>
 3 #include <iostream>
 4 using namespace std;
 5 double SavingsAccount::total = 0;
 6 SavingsAccount::SavingsAccount(const Date& date, const string& id, double rate) :id(id), balance(0), rate(rate), lastDate(date), accumulation(0) {
 7     date.show();
 8     cout << "\t#" << id << "created" << endl;
 9 }
10 void SavingsAccount::record(const Date& date, double amount, const string& desc) {
11     accumulation = accumulate(date);
12     lastDate = date;
13     amount = floor(amount * 100 + 0.5) / 100;
14     balance += amount;
15     total += amount;
16     date.show();
17     cout << "t\#" << id << "\t" << amount << "\t" << balance << "\t" << desc << endl;
18 }
19 void SavingsAccount::error(const string& msg) const {
20     cout << "Error(# " << id << " ): " << msg << endl;
21 }
22 void SavingsAccount::deposit(const Date & date, double amount, const string & desc) {
23     record(date, amount, desc);
24 }
25 void SavingsAccount::withdraw(const Date & date, double amount, const string& desc) {
26     if (amount > getBalance())
27         error("not enough money");
28     else
29         record(date, -amount, desc);
30 }
31 void SavingsAccount::settle(const Date& date) {
32     double interest = accumulate(date) * rate//计算年息
33                       / date.distance(Date(date.getYear() - 1, 1, 1));
34     if (interest != 0)
35         record(date, interest, "interest");
36     accumulation = 0;
37 }
38 void SavingsAccount::show() const {
39     cout << "ID: "<< id << "\tBalance:" << balance;
40 }
View Code

6_25.cpp代码:

 1 #include "account.h"
 2 #include <iostream>
 3 using namespace std;
 4 int main() {
 5 
 6     Date date(2008, 11, 1);
 7     SavingsAccount accounts[] = {
 8         SavingsAccount(date,"03755217",0.015),
 9         SavingsAccount(date, "02342342", 0.015)
10     };
11     const int n = sizeof(accounts) / sizeof(SavingsAccount); 
12 
13     accounts[0].deposit(Date(2008, 11, 5), 5000, "salary");
14     accounts[1].deposit(Date(2008, 11, 25), 10000, "sell stock 0323");
15 
16     accounts[0].deposit(Date(2008, 12, 5), 5500, "salary");
17     accounts[1].withdraw(Date(2008, 12, 20), 4000, "buy a laptop");
18 
19     cout << endl;
20     for (int i = 0; i < n; i++) {
21         accounts[i].settle(Date(2009, 1, 1));
22         accounts[i].show();
23         cout << endl;
24     }
25     cout << "Total: " << SavingsAccount::getTotal() << endl;
26     return 0;
27 }
View Code

运行截图:

 

标签:std,const,cout,对象,int,实验,include,string
From: https://www.cnblogs.com/yr123/p/18525842

相关文章

  • 实验3
    实验任务1:button.hcpp#pragmaonce#include<iostream>#include<string>usingstd::string;usingstd::cout;//按钮类classButton{public:Button(conststring&text);stringget_label()const;voidclick();private:strin......
  • 实验4 C语言数组应用编程
    实验任务1:task1.c源代码:1#include<stdio.h>2#defineN43#defineM245voidtest1(){6intx[N]={1,9,8,4};7inti;89printf("sizeof(x)=%d\n",sizeof(x));1011for(i=0;i<N;++i)......
  • 实验4
    任务11#include<stdio.h>2#defineN43#defineM245voidtest1(){6intx[N]={1,9,8,4};7inti;89printf("sizef(x)=%d\n",sizeof(x));1011for(i=0;i<N;++i)12printf("%p:%d\n",&x[i......
  • 实验3
    任务1button.hpp1#pragmaonce23#include<iostream>4#include<string>56usingstd::string;7usingstd::cout;89//按钮类10classButton{11public:12Button(conststring&text);13stringget_label()const;1......
  • 4.3软件设计:面对对象的设计
    面对对象设计1、面对对象的架构设计1.1第一步:构造系统的物理模型1.2第二步:设计子系统划分各个子系统的方式定义子系统之间的关系定义子系统的接口1.3第三步:非功能需求设计2、面对对象的用例设计与类设计2.1类2.2类间关系2.3细化用例第一步:定义类的属性第二步:定义......
  • 实验4
    Task1#include<stdio.h>#defineN4#defineM2voidtest1(){ intx[N]={1,9,8,4}; inti; //输出数组x所占用的字节 printf("sizeof(x)=%d\n",sizeof(x)); //输出每个元素占据的地址以及值 for(i=0;i<N;i++) printf("%p:%d\n",&x[i],x[i]); //输出数组x对应的值 pri......
  • 实验4
    #include<stdio.h>#defineN4#defineM2voidtest1(){intx[N]={1,9,8,4};inti;printf("sizeof(x)=%d\n",sizeof(x));for(i=0;i<N;++i)printf("%p:%d\n",&x[i],x[i]);prin......
  • 实验3 类和对象_基础编程2
    实验任务1:代码:1#pragmaonce23#include<iostream>4#include<string>56usingstd::string;7usingstd::cout;89//按钮类10classButton{11public:12Button(conststring&text);13stringget_label()const;14......
  • 实验4 c语言数组应用编程
    task1:1#include<stdio.h>2#include<stdlib.h>3#defineN44#defineM2567voidtest1(){8intx[N]={1,9,8,4};9inti;1011printf("sizeof(x)=%d\n",sizeof(x));1213for(i=0;i<N;++i)14......
  • 实验四
    实验1#include<stdio.h>#defineN4#defineM2voidtest1(){intx[N]={1,9,8,4};inti;//输出数组x占用的内存字节数printf("sizeof(x)=%d\n",sizeof(x));//输出每个元素的地址、值for(i=0;i<N;++i)......