4.创建私有属性以及需要注意的点
#include<iostream>
using namespace std;
class Student
{
private:
string s_name;
int s_age;
public:
void getname(string name)
{
s_name = name;
}
//我们只是写入了student的姓名,不可以读取
void showinf()
{
cout << s_name << endl;
}
//进行读取
void getid(int age)
{
s_age = age;
}
};
int main()
{
Student stu;
stu.getname("小明");
stu.getid(1);
stu.showinf();
return 0;
}
注意:私有属性只能通过调用特定的函数进行修改,不能直接访问
5.实例
#include<iostream>
using namespace std;
class Cube
{
private:
int x;//长
int y;//宽
int z;//高
public:
void getx(int X)
{
x = X;
}
void gety(int Y)
{
y = Y;
}
void getz(int Z)
{
z = Z;
}
void area()
{
int area = 2 * (x * y + x * z + y * z);
cout << "立方体的面积为:" << area << endl;
}
void volume()
{
int volume = x * y * z;
cout << "立方体的体积为:" << volume << endl;
}
};
int main()
{
Cube cube;
cube.getx(2);
cube.gety(3);
cube.getz(4);
cube.area();
cube.volume();
return 0;
}