构造函数和析构函数
#include<iostream>
using namespace std;
class person
{
public:
int age;
//构造函数
person()
{
cout << "调用无参构造函数" << endl;
}
person(int a)
{
age = a;
cout << "调用有参构造函数" << endl;
}
~person()
{
cout << "调用析构函数" << endl;
}
//拷贝构造函数
person(const person& p)
{
age = p.age;
cout << "调用拷贝构造函数" << endl;
}
};
//调用
void test()
{
//括号法
person p1;
person p2(20);//构造函数
person p3(p2);//拷贝构造函数
cout << p2.age << endl;
cout << p3.age << endl;
//显示法
person p2 = person(10);
person p2 = person(p3);
//隐式法
person p4 = 10;
}
int main()
{
test();
}
#include<iostream>
#include<cstring>
using namespace std;
class Student
{
public:
string name;
int id;
void showstudent()
{
cout << "name " << name << endl;
cout << "id " << id << endl;
}
void setname(string pname)
{
name = pname;
}
};
int main()
{
Student s1;
s1.name = "zhangsan";
s1.setname("666");
s1.id = 1;
s1.showstudent();
Student s2;
s2.name = "lisi";
s2.id = 2;
s2.showstudent();
}
封装,访问权限
公共 public 类内类外均可访问
保护 protected 类内可以类外不可以(继承:父亲的保护,儿子可以访问)
私有 private 类内可以类外不可以(继承:父亲的私有,儿子不可以访问)
struct和class的区别:默认的访问权限不同
struct默认公共,class默认私有
#include<iostream>
#include<cstring>
using namespace std;
class Person
{
public:
void setname(string name)//设置姓名 用公有方法去访问私有成员
{
m_Name = name;
}
string getname()//获取姓名
{
return m_Name;
}
int getage()//读取年龄
{
return m_Age;
}
void setidol(string idol)
{
m_Idol = idol;
}
private:
string m_Name;//姓名 可读可写
int m_Age=18;//年龄 只读
string m_Idol;//偶像 只写
};
int main()
{
Person p;
p.setname("zhangsan");
cout <<"姓名:"<<p.getname()<< endl;
//p.m_Age = 10;无法修改年龄,因为年龄是私有成员,只读。
cout << "年龄:" << p.getage() << endl;
p.setidol("小明");
//cout << p.m_Idol;此idol为私有成员,没有读取方法
}
//设置年龄(0~150)
void setage(int age)
{
if (age < 0 || age>150)
{
cout << "输入有误" << endl;
return;
}
m_Age = age;
}
拷贝构造函数使用时机
#include<iostream>
#include<cstring>
using namespace std;
//拷贝构造函数使用时机:
//1.使用已经创建完毕的对象来初始化一个新对象
//2.值传递的方式给函数参数传值
//3.值方式返回局部对象
class Person
{
public:
int m_Age;
Person()
{
cout << "调用默认构造函数" << endl;
}
Person(int age)
{
m_Age = age;
cout << "调用有参构造函数" << endl;
}
Person(const Person& p)
{
cout << "调用拷贝构造函数" << endl;
m_Age = p.m_Age;
}
~Person()
{
cout << "调用析构函数" << endl;
}
};
//1.使用已经创建完毕的对象来初始化一个新对象
void test01()
{
Person p1(20);
Person p2(p1);
cout << "p2年龄为 " << p2.m_Age << endl;
}
//2.值传递的方式给函数参数传值
void dowork(Person p)
{
}
void test02()
{
Person p;
dowork(p);
}
//3.值方式返回局部对象
void dowork02()
{
Person p1;
return p1;
}
void test03()
{
}
int main()
{
//test01();
test02();
}
没听完
定义的p和传入的p不影响。