类和对象,this指针

C++ OOP编程,this指针

C: 各种各样的函数的定义 struct

C++: 类=>实体的抽象类型

实体(属性、行为)->ADT(abstract data type)

对象<-(实例化)类(属性->成员变量 行为->成员方法)

OOP语言的四大特征是什么?

抽象 封装/隐藏 继承 多态

example:类->商品实体

访问限定符:public公有的 private私有的 protected保护的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <iostream>
#include <string.h>
using namespace std;
const int NAME_LEN = 20;
class CGoods //商品的抽象数据类型
{

public: //给外部提供公有的方法,来访问私有的属性
//做商品初始化用的
//怎么知道把信息初始化给哪一个对象
void init(const char *name, double price, int amount);
//打印商品信息
//怎么知道处理那个对象的信息
//类的成员方法一经编译,所有的方法参数,都会加一个this指针,接收调用该方法的对象的地址
void show();
//给成员变量提供一个getXXX或setXXX的方法
//类内体实现的方法,自动处理成内联函数
void set_name(char *name)
{
strcpy(_name, name);
}
void set_price(double price)
{
_price = price;
}
void set_amount(int amount)
{
_amount = amount;
}
const char *get_name()
{
return _name;
}
double get_price()
{
return _price;
}
int get_amount()
{
return _amount;
}

private: //属性一般都是私有的成员变量
char _name[NAME_LEN];
double _price;
int _amount;
};
void CGoods::init(const char *name, double price, int amount)
{
strcpy(this->_name, name);
this->_price = price;
this->_amount = amount;
}
void CGoods::show()
{
cout << "name:" << this->_name << endl;
cout << "price:" <<this->_price << endl;
cout << "amount:" << this->_amount << endl;
}
int main()
{
/*
CGoods可以定义无数的对象,每一个对象都有自己的成员变量
但是它们共享一套成员方法
*/
CGoods good;
//cout<<good.price<<endl;私有的不能访问
//init(&good,"blocks",10.0,200);
good.init("blocks", 10.0, 200);
good.show();
good.set_price(20.5);
good.set_amount(100);
good.show();
CGoods good2;
good2.init("空调", 10000, 50);
good2.show();
return 0;
}