c++ 类

最近新学习类,我整理了一下自己的学习心得和体会。

类有三个重要的特征,即封装、继承和多态。

      简单结构体应用

#include <iostream>
using namespace std;
struct Dot{
	int a;
	int b;
};
int main(){
		Dot dot;
		dot.a=0;
		dot.b=1;
		cout<<"dot.a="<<dot.a<<endl;
		cout<<"dot.b="<<dot.b<<endl;
	system("pause");
	return 0;
}
    

#include <iostream>
using namespace std;
struct Dot{
	int a;
	int b;
	void print(){
		cout<<"a="<<a<<endl;
		cout<<"b="<<b<<endl;
	}
};
int main(){
		Dot dot;
		dot.a=0;
		dot.b=1;
		dot.print();
	system("pause");
	return 0;
}

#include <iostream>
using namespace std;
class Dot{
public:
	int a;
	int b;
	void print(){
		cout<<"a="<<a<<endl;
		cout<<"b="<<b<<endl;
	}
};
int main(){
		Dot dot;
		dot.a=0;
		dot.b=1;
		dot.print();
	system("pause");
	return 0;
}


   结构体在默认情况下,其成员是共有的,类在默认情况下,其成员是私有的,这事结构体和类的区别之一。


#include <iostream>
using namespace std;
class Rectangle{
private:
	double length,width;
public:
	Rectangle(double a,double b);
	void area(){
		cout<<"Area of Rectangle is:"<<length*width<<endl;
	}
};

Rectangle::Rectangle(double a,double b){
	length=a;
	width=b;
}
int main(){
	Rectangle rect(2,9);
	rect.area();
	system("pause");
	return 0;
}

在主函数main()中,没有直接调用该构造函数Rectangle(),只是声明了对象rect,系统自动调用了构造函数并完成了初始化的功能。

    如果涉及带有默认参数的构造函数,在定义对象时必须给构造函数传递参数,否则构造函数不被执行。而实际应用中,也可以把构造函数定义成带有默认参数值的构造函数,这样在定义对象时可以不指定实参,用默认参数值来初始化数据成员。

#include <iostream>
using namespace std;
class Rectangle{    //定义类
private:
	double length,width;    //定义私有数据成员
public:
	Rectangle(double a=0.0,double b=0.0);	//声明带有默认参数的构造函数
	double area();							//声明成员函数
};
Rectangle::Rectangle(double a ,double b){	//定义构造函数
	length=a;
	width=b;								//数据成员初始化
}
double Rectangle::area(){					//定义成员函数
	double s;
	s=length*width;
	return s;								//返回面积
}
int main(){
	Rectangle ob1;							//创建对象1
	Rectangle ob2(1.5,2.0);					//创建对象2
	Rectangle ob3(2.5);						//创建对象3
	cout<<ob1.area()<<endl;
	cout<<ob2.area()<<endl;
	cout<<ob3.area()<<endl;
	system("pause");
	return 0;
}
//ob1在定义时没有传递参数,所以length和width取构造函数的默认值初始化值0.0,对象3则将2.5传递给第一个length。




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值