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;
}