对象:一切都可为对象,类:相同特性的对象;面向对象特性:封装,继承,多态
一,封装
CLASS 类名 { 访问权限 :属性/行为 }
实例化:通过一个类,创建一个对象
#include<iostream>
using namespace std;
#define PAI 3.14159
class Circle //创建⚪类
{
public://访问权限:公共权限
int m_r;//属性:半径
double calculateZC()//行为:获取圆的周长,此用函数
{
return 2 * PAI * m_r;
}
};
int main()
{
Circle c1;//通过⚪类,创建对象
c1.m_r = 10;//赋值
cout << "⚪的周长为" << c1.calculateZC() << endl;
return 0;
system("pause");
}
属性+行为--》成员,属性——成员属性,成员变量;行为——成员函数,成员方法
#include<iostream>
using namespace std;
#define PAI 3.14159
class Student
{
public:
string s_name;//属性
int s_id;
void showstudent()//行为
{
cout << "姓名\t" << s_name << endl;
cout << "学号\t" << s_id << endl;
}
void setname(string name)
{
s_name = name;
}
void setid(int id)
{
s_id = id;
}
};
int main()
{
Student s1;
s1.s_name = "王五";
s1.s_id = 1242;
s1.showstudent();
/*cin >> s1.s_name >> s1.s_id;
s1.showstudent();*/
s1.setname("张三");
s1.showstudent();
s1.setid(78992342394);
s1.showstudent();
return 0;
system("pause");
}
1.1 三种权限
类内外都可:PUBLIC ,
类内可,类外不可:PRIVATE (儿子可以访问父亲的保护内容), PROTECTCED (儿子不可以访问父亲的私有内容)
#include<iostream>
using namespace std;
#define PAI 3.14159
class Person
{
public:
string p_name;
protected:
string p_car;
private:
int p_password;
public:
void func()//类内访问
{
p_name = "张三";
p_car ="小米SU7";
p_password = 4234235;
cout << p_name << " " << p_car << " " << p_password << endl;
}
};
int main()
{
Person p1;
p1.func();
p1.p_name = "大哥";
//p1.p_car = "小米SU7";类外不可访问
//p1.p_password = 4234235;
p1.func();
//哈哈,运行这个函数就会赋值
cout << p1.p_name << endl;
p1.p_name = "大哥";
cout << p1.p_name << endl;
return 0;
system("pause");
}
1.2 STRUCT 和 CLASS的区别
STRUCT默认权限是公共,CLASS默认权限是私有
#include<iostream>
using namespace std;
#define PAI 3.14159
class P1//默认私有
{
int m_a;
};
struct P2//默认公共
{
int m_a;
};
int main()
{
P1 pp1;
//pp1.m_a = 3245;不可访问
P2 pp2;
pp2.m_a = 3245;
return 0;
system("pause");
}
1.3 成员属性设置为私有
优点:自己控制读写权限;对于写权限,可以检测数据的有效性
#include<iostream>
using namespace std;
#define PAI 3.14159
class P1//默认私有
{
public:
void setname(string name)//设置NAME
{
m_name = name;
}
string getname()//读取NAME
{
return m_name;
}
int getage()
{
return m_age;
}
void settage(int age)
{
if (age < 0 || age>150)
{
cout << "年龄" << age << "数据有误,输入失败" << endl;
return;
}
else
{
m_age = age;
}
}
void setidol(string idol)
{
m_idol = idol;
}
private:
string m_name;//可读可写
int m_age=18;//只读
string m_idol;//只写
};
int main()
{
P1 per1;
per1.setname("拉拉");
cout << per1.getname() << endl;
//m_age = 20;
//per1.setage(20);没有设置
cout << per1.getage() << endl;
per1.settage(900);
cout << per1.getage() << endl;
per1.settage(90);
cout << per1.getage() << endl;
per1.setidol("大大");
//cout << per1.getidol("导弹无法去") << endl;没有设置
return 0;
system("pause");
}