C++ 类基本定义

1、类定义、初始化及成员访问

对象成员初始化/z赋值:Public类型可以直接赋值如下,而pravite 需要用到类构造函数取赋值。

#include<iostream>
using  namespace std;
class RECT {
public:
	int top{ 1 }; //类成员初始化,对象成员未初始化,可以调用此值
	int bottom{ 1 };
};

int main()
{

	RECT aRect{ 3, 4 }; //对象成员初始化
	RECT* PaRect;
	PaRect = &aRect;
	cout << (*PaRect).top; //指针访问对象成员
	cout << PaRect->bottom;//指针间访对象成员
	return 0;
}

2、类成员函数

2.1内部定义成员函数

#include<iostream>
using  namespace std;
class Box {
public:
	int Lenght{ 1 };
	int width {1 };
    int height{ 1 };
	int volume()
	{
		return Lenght * width * height;
	}
};

int main()
{

	Box box1{ 1,3, 4 }; //对象成员初始化
	cout << box1.volume()<<endl; //注意成员函数需要带()
	cout<<sizeof(Box) << endl;  //Box 数据类型的大小
	return 0;
}

2.2外部定义成员函数

 用函数调用和作用域::限定

#include<iostream>
using  namespace std;
class Box {
public:
	int Lenght{ 1 };
	int width {1 };
    int height{ 1 };
	int volume();// 调用函数
};
int Box::volume() //用作用域::限定
{
	return Lenght * width * height;
}
int main()
{
	Box box1{ 1,3, 4 }; //对象成员初始化
	cout << box1.volume()<<endl; //注意成员函数需要带()
	cout<<sizeof(Box) << endl;  //Box 数据类型的大小
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值