#define _CRT_SECURE_NO_WARNINGS //两种构造函数
#include <iostream>
#include<string>
class string
{
public:
char *p;
int length;
string(int num,char *str)
{
//获取长度,分配内存,拷贝内容
length = num;
p = new char [length];
memset(p, 0, length);//
strcpy(p, str);
}
string(const string & string1)
{
//qian 浅拷贝
//this->p = string1.p;
// this->length = string1.length;
//shen 深拷贝
this->p = new char[string1.length]; //开辟一块新内存
this->length = string1.length;
memset(this->p, 0, this->length);//清空内存
strcpy(this->p, string1.p);
}
~string()
{
delete[] p;//
}
};
void main3()
{
string *pstr1 = new string(10, "hello");
std::cout <<pstr1->p<< std::endl;
string *pstr2 = new string(*pstr1);//浅拷贝
delete pstr1; //删除pstr1后 内存回收 pstr2指向无用内存
std::cout << pstr2->p << std::endl;
std::cin.get();
}
void main1()
{
string str1(10, "hello");
std::cout << str1.p << std::endl;
string str2(str1);
std::cout << str2.p << std::endl;
std::cin.get();
}
//delete可以禁用默认生成的函数,禁用构造可以无法实例化 //delete和default
//禁用拷贝构造,可以实现禁止别人拷贝你
//default默认存在
class myclassA
{
public:
//myclassA::myclassA(void)”: 尝试引用已删除的函数
myclassA() = delete; //默认删除构造函数,无法实例化
myclassA() = default; //默认存在
myclassA(const myclassA &) = delete;//禁用拷贝构造函数
myclassA(const myclassA &) = default; //默认存在
//=
~myclassA();
};
void main211()
{
//myclassA myclassa1;
//myclassA myclassa2(myclassa1);
//myclassA myclassa3 = myclassa1;//重载了=,根据类型
// myclassA a1;
}
#include<iostream> //两种初始化方式
// 编译器会生成默认的构造函数和拷贝构造函数,但如果声明已经定义,便不会生成。
class classA
{
private:
int a;
int b;
public:
//classA(int x, int y)
//{
// a = x;
// b = y;
//} 两种初始化方式(1)
classA(int x, int y):a(x), b(y)
{
}//(2)
void print()
{
std::cout <<a << b << std::endl;
}
//classA(const classA &ca);
//
};
void main()
{
classA class1(10,100);//编译器会默认生成默认的构造函数
classA class2(class1);//编译器会生成默认的拷贝构造函数
class1.print();
class2.print();//默认的拷贝构造函数
//classA class3(4);
std::cin.get();
}