认识C++中的类-1

//writer:zyli
//date:20190622
//构建rectangle类,认识类:
#include
using namespace std;
class rectangle{
//private修饰的成员变量只有类内可直接访问,类的实例要通过成员函数才可以访问 ;
private:
int length;
int width;
int area;
//public修饰的成员变量,实例可以直接访问;
public:
void set_length(int len);
void set_width(int wide);
void print_area();
int test=10;
};

void rectangle::set_length(int len)
{
cout<<“set length”<<endl;
this->length=len;
cout<<“length=”<<length<<endl;
}
void rectangle::set_width(int wide)
{
cout<<“set length”<<endl;
this->width=wide;
cout<<“width=”<<width<<endl;
}
void rectangle::print_area(){
cout<<“area=”<length*this->width<<endl;
this->test=15;
}

int main()
{
rectangle rec;
rec.set_length(5);
rec.set_width(3);
rec.print_area();
cout<<“test1=”<<rec.test<<endl;
rec.test=20;
cout<<“test2=”<<rec.test<<endl;
cout<<"-----------"<<endl;
//A.B则A为对象或者结构体
//A->B则A为指针,->是成员提取,A->B是提取A中的成员B,A只能是指向类、结构、联合的指针;
//定义rec2指向rec,则访问成员时,需要使用“rec2->test”;同时可见“this->test”也是这样;
rectangle *rec2=&rec;
rec2->test=30;
cout<<“test3=”<test<<endl;
cout<<“test4=”<<rec.test<<endl;
rec2->print_area();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值