Chapter 7.1.2

  • this 

默认情况下,this的类型是指向类类型非常量版本的常量指针。

相当于:

类名 *const


顶层const, 所以不能改变this指针指向的对象(即那个地址),可以改变指向对象的值,我们当然不能把this绑定到一个常量对象上。

为了让我们能在一个常量对象上调用普通的成员函数,我们可以把this设置为指向常量的指针有助于提高函数的灵活性。

c++允许把const关键字放在成员函数的参数列表之后,表示this是一个指向常量的指针,像这样使用const的成员函数被称为常量成员函数。

 std::string Sales_data::isbn(const Sales_data *const this){ return this->isbn; }

this是指向常量的指针,所以常量成员函数不能改变调用它的对象的内容,即只能读,不能写。

 

一个Sales_data类如下:

 1 #ifndef SALES_DATA_H
 2 #define SALES_DATA_H
 3 
 4 
 5 struct Sales_data {
 6     //新成员:关于Sales_data对象的操作
 7     std::string isbn() const { return bookNo; }
 8     Sales_data& combine(const Sales_data&);
 9     double avg_price() const;
10     //数据成员
11     std::string bookNo;
12     unsigned units_sold = 0;
13     double revenue = 0.0;
14 };
15 //Sales_data的非成员接口函数
16 Sales_data add(const Sales_data&, const Sales_data&);
17 std::ostream &print(std::ostream&, const Sales_data&);
18 std::istream &read(std::istream&, Sales_data&);
19 double Sales_data::avg_price() const{
20     if(units_sold)
21         return revenue/units_sold;
22     else
23         return 0;
24 }
25 Sales_data& Sales_data::combine(const Sales_data &rhs){
26     units_sold += rhs.units_sold;
27     revenue += rhs.revenue;
28     return *this;
29 }
30 #endif

 

7.2 曾在2.6.2节的练习中编写了一个Sales_data类,请向这个类添加combine和isbn成员。

 如上Sales_data头文件代码

 

7.3 修改7.1.1节的交易处理程序,令其使用这些成员。

 

 1 #include<iostream>
 2 #include "Sales_data.h"
 3 using namespace std;
 4 int main()
 5 {
 6     Sales_data item;
 7     item.bookNo = "123";
 8     item.units_sold = 10;
 9     item.revenue = 5;
10 
11     if(item.units_sold != 0){
12         Sales_data item1;
13         item1.bookNo = "123";
14         item1.units_sold = 10;
15         item1.revenue = 5;
16         if(item.isbn() == item1.isbn()){
17             item1.combine(item1);
18         }
19         else{
20             cout << item1.bookNo;
21             item.bookNo = item1.bookNo;
22             item.revenue = item1.revenue;
23             item.units_sold = item.units_sold;
24         }
25         cout << item.units_sold;
26     }
27     else{
28         cerr << "No data?" << endl;
29     }
30     return 0;
31 }

 

7.4 编写一个名为Person的类,使其表示人员的姓名和地址。使用string对象存放这些元素,接下来的练习将不断充实这个类的其他特征。

1 #include<iostream>
2 #include<string>
3 
4 class Person{
5 private:
6     string name;
7     string address;
8 };
1 #include<iostream>
2 #include<string>
3 
4 struct Person{
5     string name;
6     string address;
7 };

 

7.5 在你的Person类中提供一些操作使其能够返回姓名和住址。这些函数是否应该是const的呢?解释原因。

1 #include<iostream>
2 #include<string>
3 
4 struct Person{
5     string name;
6     string address;
7 string getName() const{ return name;} 8 string getAddress() const{ return address;} 9 };

this指针是 *const型,即不能改变指向的对象(地址),函数功能只为返回值,则让this指针指向常量。

posted @ 2018-03-29 21:45  抹茶奶绿不加冰  阅读(153)  评论(0编辑  收藏  举报