面向对象编程:
class CGoods
{
public:
char Name[20];
int Amount;
float Price;
float Total_value;
};
在上述语句的基础上需要:
CGoods c1; this=>&c1;
CGoods *this; *this=>c2;
this=&c1; (*this).Price=10;
c1.Price=10; this->Price=10;
不可直接为Price赋值
正确认识this指针:
(1)识别和记录类体中属性的名称,类型和访问限定,与属性在类体中的位置无关;
(2)识别和记录类体中函数原型(返回类型 + 函数名 + 参数列表),形参的默认值,访问限定,不识别函数体
(3)改写在类中定义的函数的参数列表和函数体,改写对象调用成员函数的形式;
举例说明在C++中如何正确使用类:
#include <iostream>
#include <stdio.h>
#include<string>
using namespace std;
class CGoods
{
private:
char Name[20];
int Amount;
float Price;
float Total_value;
public:
//void RegisterGoods(CGoods *this,const char*,int float);
void RegisterGoods(const char*, int, float);//输入数据
//void CountTotal(CGoods *this)
void CountTotal() //计算商品总价值
{
Total_value = Amount * Price;
}
//void GetName(CGoods *this,char name [])
void GetName(char name[]) //读取商品名
{
strcpy_s(name, 20, Name);
}
//INT GetAmount(CGoods *this)
int GetAmount() //读取商品数量
{
return Amount;
}
//float GetPrint(CGoods *this)
float GetPrice() //读取商品单价
{
return Price;
}
//float GetTotal_value(CGoods *this)
float GetTotal_value() //读取商品总价值
{
return Total_value;
}
};
//void CGoods::RegisterGoods(CGoods *this,const char* name,int amount,float price)
void CGoods::RegisterGoods(const char* name, int amount, float price)
{
strcpy_s(this->Name, 20, name);
this->Amount = amount;
this->Price = price;
}
int main()
{
CGoods c1, c2;
c1.RegisterGoods("iphone", 10, 6800);
//RegisterGoods(&c1,"iphone",10,6800);
c1.CountTotal();
c2.RegisterGoods("huawei", 12, 7800);
//RegisterGoods(&c2,"huawei",12,7800);
c2.CountTotal();
}