C语言实训周笔记(7)

本文通过一个CGoods类的实例,展示了C++中面向对象编程的基本概念,包括类的定义、对象的创建以及成员函数的使用。CGoods类包含了商品的名称、数量和价格等属性,并提供了注册商品、计算总价值、获取属性值等方法。在main函数中,我们创建了两个CGoods对象c1和c2,并分别进行了商品信息的注册和总价的计算,演示了如何调用类的成员函数。
摘要由CSDN通过智能技术生成

面向对象编程:

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();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值