1、封装–属性和行为
#include<iostream>
using namespace std;
const double PI = 3.14;
class Circle
{
public:
int m_r;
double calculateZC()
{
return 2 * PI*m_r;
}
};
int main()
{
Circle c1;
c1.m_r = 10;
cout << "周长:" << c1.calculateZC() << endl;
system ("pause");
return 0;
}
2、访问权限
#include<iostream>
#include<string>
using namespace std;
class Person
{
public:
string m_Name;
protected:
string m_Car;
private:
int m_Password;
public:
void func()
{
m_Name = "张三";
m_Car = "拖拉机";
m_Password = 1234;
}
};
int main()
{
Person p1;
p1.m_Name = "李四";
system ("pause");
return 0;
}
3、成员属性私有化
#include<iostream>
#include<string>
using namespace std;
class Person
{
public:
void setName(string name)
{
m_Name = name;
}
string getName()
{
return m_Name;
}
int getAge()
{
return m_Age;
}
void setAge(int age)
{
if (age < 0 || age>150)
{
m_Age = 0;
cout << "年龄有误!" << endl;
}
else
m_Age = age;
}
void setLover(string Lover)
{
m_Lover = Lover;
}
private:
string m_Name;
int m_Age;
string m_Lover;
};
int main()
{
Person p;
p.setName("张三");
p.setAge(1000);
cout << p.getName()<< endl;
cout << p.getAge() << endl;
cout << p.getAge() << endl;
p.setLover("小红");
system ("pause");
return 0;
}