- 成员属性设为私有的好处:自己控制读写权限,set和get函数;对于写权限,判断传入参数的有效性
#include <iostream>
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 = 123456;
}
};
int main_12() {
Person p;
p.m_Name = "李四";
system("pause");
return 0;
}
- 构造函数和析构函数
构造函数 类名,没有返回值,只会被调用一次
析构函数,销毁前,只会被调用一次
#include <iostream>
using namespace std;
class People
{
public:
People()
{
cout << "Person的构造函数调用" << endl;
}
~People()
{
cout << "Person的析构函数的调用" << endl;
}
};
void test11()
{
People p;
}
int main_13() {
People p;
system("pause");
return 0;
}
- 构造函数的分类和调用
#include <iostream>
using namespace std;
class Person1
{
public:
Person1() {
cout << "无参构造函数" << endl;
}
Person1(int a) {
age = a;
cout << "有参构造函数!" << endl;
}
Person1(const Person1& p) {
age = p.age;
cout << "拷贝构造函数!" << endl;
}
~Person1()
{
cout << "析构函数!" << endl;
}
public:
int age;
};
void test01() {
Person1 p;
}
void test02() {
Person1 p1(10);
Person1 p2 = Person1(10);
Person1 p3 = Person1(p2);
cout << Person1(10).age << endl;
Person1 p4 = 10;
Person1 p5 = p4;
}
int main_14() {
test01();
test02();
system("pause");
return 0;
}