#pragma warning(disable:4996)
#include <iostream>
#include <string.h>
using namespace std;
class Test
{
public:
Test()
{
this->name = nullptr;
cout << "Test" << endl;
}
Test() = default; 声明无参构造函数使用系统默认生成的;
Test() = delete;不让系统默认生成无参构造函数
Test(int num, const char* name, int age)
{
this->num = num;
this->age = age;
//this->name = name;//error;
int len = strlen(name);
this->name = new char[len + 1];
strcpy(this->name, name);
cout << "Test int char * int" << endl;
}
Test(int num, int age)
{
this->num = num;
this->age = age;
this->name = nullptr;
cout << "Test int int" << endl;
}
Test(const Test& other)
{
this->num = other.num;
this->age = other.age;
//this->name = other.name;
int len = strlen(other.name);
this->name = new char[len + 1];
strcpy(this->name, other.name);
cout << "Test copy Test" << endl;
}
explicit Test(int num) //防止发生隐式转换
{
this->num = 0;
this->age = 0;
this->name = nullptr;
cout << "Test int" << endl;
}
explicit Test(const char* name)
{
this->name = nullptr;
this->num = 0;
this->age = 0;
}
Test(Test&& other)//移动拷贝拷贝构造函数
{
this->num = other.num;
this->age = other.age;
this->name = other.name;
other.name = nullptr;
cout << "Test copy Test &&" << endl;
}
~Test()
{
if (name != nullptr)
{
delete[] name;
}
cout << "~Test" << endl;
}
int num;
char* name;//string name;
int age;
};
无参构造函数:系统默认生成、自定义 (default、delete)
有参构造函数:可以重载;
拷贝构造函数(用已有的对象初始化新的对象):默认拷贝构造函数(问题:浅拷贝问题) 自定义拷贝构造函数(深拷贝)
拷贝构造函数的调用时机:
- 用已有的对象初始化新的对象
- 传参:当形参为类的对象时,传参时会调用拷贝构造函数;
- 函数返回值为对象时;
类型转换构造函数:构造函数只有一个参数的,都是类型转换构造函数;用explicit防止发生类型转换;
移动拷贝构造函数: 解决临时对象拷贝效率问题;
void test1(Test t)
{
cout << t.name << endl;
}
Test test2()
{
Test temp(1, "lisi", 24);
return temp;
}
int main()
{
#if 0
Test t; //调用无参构造函数:默认的无参构造函数(类里没有任何构造函数时,系统会默认生成)
Test t1(1, "zhangsan", 21); //有参构造函数
Test t2(2, 23);
Test t3(t1);
//cout << t3.num << " " << t3.name << endl;
//Test t4 = 1; //调用类型转换构造函数! 危险(隐式类型转换:其他可以转换成类类型)
Test t5(1);
//Test t6 = "hello world";
Test t7;
//t7 = 1;
#endif
Test t1(1, "zhangsan", 24);
test1(t1);
Test t2 = test2();
return 0;
}
#include <iostream>
#include <string>
#include <string.h>
using namespace std;
class MyString
{
public:
MyString(const char *ptr)
{
int len = strlen(ptr);
this->ptr = new char[len + 1];
strcpy(this->ptr,ptr);
}
int size()
{
return strlen(ptr);
}
int at(int index)
{
return ptr[index];
}
const char * c_str()
{
return ptr;
}
private:
char *ptr;
};
int main()
{
string s1('a',100);
string s2("hello world");
string s3(s2);
s1.size();
const char *temp = s2.c_str();
MyString mys1("hello world");
cout << mys1.at(1) << endl;
temp = mys1.c_str();
return 0;
}