类的简单定义:类是用户定义的一种数据类型,它将数据表示和操纵数据的方法整合成一个简洁的包
对象的简单定义:对象是根据这些描述创建的实体
类:
举个例子,我们将创建一个Fruit类,如下(函数部分未展示):
class Fruit{
private:
int weight;
int price;
public:
void show();
void count();
};
定义了一个类,类的名字叫Fruit
Fruit里面的private:是表示这是私有的,也就是说,int weight;和int price ;创造的变量weight和price不能直接访问。
public:表示这是公开的,可以直接访问,show()和count()函数可以直接访问。
那变量weight和price怎么修改?
通过接口函数,也就是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;
}
编程之路刚刚开始,未来的路还很长,加油!