类和对象简单介绍

类的简单定义:类是用户定义的一种数据类型,它将数据表示操纵数据的方法整合成一个简洁的包

对象的简单定义:对象是根据这些描述创建的实体

类:

举个例子,我们将创建一个Fruit类,如下(函数部分未展示):

class Fruit{
private:
    int weight;
    int price;
public:
    void show();
    void count();

};

定义了一个类,类的名字叫Fruit

Fruit里面的private:是表示这是私有的,也就是说,int weight;int price ;创造的变量weightprice不能直接访问。

public:表示这是公开的,可以直接访问,show()count()函数可以直接访问。

那变量weightprice怎么修改?

通过接口函数,也就是public:里面的函数进行修改,可以自己在public:里面定义一个change()函数进行修改

类的完整函数:
class Fruit{
private:
    int weight=10;
    int price=1;
public:
    void show();//展示weight和price的函数
    void count();//进行计算的函数
    void change();//修改变量的函数

};
void Fruit::show(){

cout<<"the weight is "<<weight<<endl;
cout<<"the price is "<<price<<endl;

}
void Fruit::count(){

int num=weight*price;
cout<<"the count is "<<num<<endl;

}

void Fruit::change(){

cout<<"input the number that to change weight"<<endl;
cin>>weight;
cout<<"input the number that to change price"<<endl;
cin>>price;
}

对象:

接下来,就是讲对象,对象是什么,就是类的具体实例。

我们创建了一个类,名字叫Fruit,对吧,接下来,我们创建一个对象


int main(){

Fruit apple;

return 0;
}

Fruit apple;这句话就是创建了一个对象

对象是apple

接口函数的使用:


int main(){

Fruit apple;
apple.show();
apple.change();
apple.show();

return 0;
}

使用方法也很简单,就是在对象apple后面加一个“.”,再加上函数就OK了

完整能运行的代码如下,你可以添加一个没用到的函数count()尝试一下,看完了,T喵的啥也不干,等于白学

#include<iostream>
using namespace std;
class Fruit{
private:
    int weight=10;
    int price=1;
public:
    void show();//展示weight和price的函数
    void count();//进行计算的函数
    void change();//修改变量的函数

};
void Fruit::show(){

cout<<"the weight is "<<weight<<endl;
cout<<"the price is "<<price<<endl;

}
void Fruit::count(){

int num=weight*price;
cout<<"the count is "<<num<<endl;

}

void Fruit::change(){

cout<<"input the number that to change weight"<<endl;
cin>>weight;
cout<<"input the number that to change price"<<endl;
cin>>price;
}


int main(){

Fruit apple;
apple.show();
apple.change() ;
apple.show();

return 0;
}

 编程之路刚刚开始,未来的路还很长,加油!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值