浅拷贝与深拷贝
#include<iostream>
#include<string>
using namespace std;
// 系统提供的拷贝函数,只会做简单的值拷贝
// 如果类中有属性开辟到堆区,那么在释放的时候,由于浅拷贝问题导致堆区内容会重复释放程序down掉 利用深拷贝 解决浅拷贝带来的问题
class Persion
{
public:
Persion(const char *name,int age)
{
p_name = (char *)malloc(strlen(name) + 1);
strcpy_s(p_name,strlen(name)+1,name);
p_age = age;
}
/*Persion(const Persion &p)
{
p_age = p.p_age;
p_name = (char*)malloc(strlen(p.p_name)+1);
strcpy_s(p_name, strlen(p.p_name) + 1, p.p_name);
}*/
/*~Persion()
{
if (p_name != NULL)
{
cout << "Persion 的析构函数调用" << endl;
free(p_name);
p_name = NULL;
}
}*/
int p_age;
char *p_name;
};
void test01()
{
Persion p1("TOM",18);
cout << "p1的姓名" << p1.p_name << endl;
Persion p2(p1);
cout << "p2的姓名" << p2.p_name << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
初始化列表
#include<iostream>
using namespace std;
class Persion
{
public:
/*Persion(int a,int b,int c)
{
m_a = a;
m_b = b;
m_c = c;
}*/
// 初始化列表 用途也是用来初始化类中的属性
Persion(int a, int b, int c) :m_a(a), m_b(b), m_c(c)
{
}
int m_a;
int m_b;
int m_c;
};
void test01()
{
// Persion p;
Persion p1(10, 20, 30);
cout << "m_a = " << p1.m_a << endl;
cout << "m_b = " << p1.m_b << endl;
cout << "m_c = " << p1.m_c << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
初始化列表:
构造函数名称():属性(值),属性(值)…
类对象作为类成员
#include<iostream>
#include<string>
using namespace std;
// 当其他类的对象作为本类的成员,先构造其它类对象,再构造自身,释放的顺序和构造是相反的
class Phone
{
public:
Phone(string pName)
{
cout << "Phone的构造函数调用" << endl;
P_name = pName;
}
~Phone()
{
cout << "Phone的析构函数调用" << endl;
}
string P_name;
};
class Game
{
public:
Game(string Gname)
{
cout << "Game的构造函数调用" << endl;
G_name = Gname;
}
~Game()
{
cout << "Game的析构函数调用" << endl;
}
string G_name;
};
class Persion
{
public:
Persion(string p_name, string pName, string Gname) :name(p_name),m_Phone(pName),m_game(Gname)
{
cout << "Persion的构造函数调用" << endl;
}
~Persion()
{
cout << "Persion的析构函数调用" << endl;
}
string name;
Phone m_Phone;
Game m_game;
};
void test01()
{
Persion("张三", "苹果", "王者荣耀");
}
int main()
{
test01();
system("pause");
return 0;
}
explicit 关键字
#include<iostream>
#include<string>
using namespace std;
class MyString
{
public:
MyString(const char * str)
{
}
// explicit 关键字用途:防止隐式类型转换方式来初始化对象
explicit MyString(int len)
{
m_len = len;
}
int m_len;
char *m_str;
};
void test01()
{
MyString str = "abc";
MyString str2 = 10;// 1、字符串长度 2、字符串
MyString str3(10);
MyString str4 = MyString(10);
}
int main()
{
test01();
system("pause");
return 0;
}