1、习题 拷贝赋值
#include <iostream>
using namespace std;
class Person
{
string const name;
int age;
char sex;
public:
Person():name("zhangsan"){cout << "Person的无参构造" << endl;}
Person(const string name,int age,char sex):name(name),age(age),sex(sex)
{cout << "Person的有参构造" << endl;}
~Person(){cout<<"Person的析构函数"<<endl;}
void show()
{
cout << "name : " << name << endl;
cout << "age : " << age << endl;
cout << "sex : " << sex << endl;
}
//实现Person的拷贝构造
Person(const Person &other):name(other.name),age(other.age),sex(other.sex)
{}
//实现Person的拷贝赋值
Person &operator = (const Person &other)
{
//如果传过来的就是类对象本身,不执行赋值操作
if(&other!=this)
{
this->age = other.age;
this->sex = other.sex;
cout<<"Person的拷贝赋值函数"<<endl;
}
return *this; // 通过this指针返回自身引用
}
};
class Stu
{
Person p1; //Stu类中包含一个Person类对象
double *p;
public:
//如果类中包含其他类的子对象,需要在构造函数的初始化列表中显性调用其他类的构造函数,完成其他类空间的构造
Stu():p(new double){cout<<"Stu的无参构造"<<endl;}
Stu(string const name,int age,char sex,double score):p1(name,age,sex),p(new double(score))
{cout << "Stu的有参构造" << endl;}
~Stu()
{
cout<<"准备释放空间"<<endl;
delete p;
cout<<"Stu的析构函数"<<endl;
}
void show()
{
p1.show();
cout<<"Stu中的show:"<<*p<<endl;
}
//实现Stu的拷贝构造
Stu(const Stu &other):p(new double(*(other.p))),p1(other.p1)
{}
//实现Stu的拷贝赋值
Stu &operator = (const Stu &other)
{
//如果传过来的就是类对象本身,不执行赋值操作
if(&other!=this)
{
this->p1 = other.p1;
*(this->p) = *(other.p);
cout<<"Stu的拷贝赋值函数"<<endl;
}
return *this; // 通过this指针返回自身引用
}
};
int main()
{
Stu s2("zhangsan",20,'m',23.9);
s2.show();
Stu s3(s2);
s3.show();
cout<<&s2<<endl;
cout<<&s3<<endl;
return 0;
}
2、完成类
#include <iostream>
#include <cstring>
using namespace std;
using namespace std;
class myString
{
private:
char *str; //记录c风格的字符串
int size; //记录字符串的实际长度
public:
//无参构造
myString() : str(new char[1]), size(0)
{
str[0] = '\0';
cout<<"无参构造"<<endl;
}
//有参构造
myString(const char* s)
{
size = strlen(s);
str = new char[size + 1];
strcpy(str, s);
cout<<"有参构造"<<endl;
}
//拷贝构造
myString(const myString &other)
{
size = other.size;
str = new char[size + 1];
strcpy(str, other.str);
cout<<"拷贝构造"<<endl;
}
//拷贝赋值函数
myString& operator=(const myString &other)
{
if (this != &other) {
delete[] str;
size = other.size;
str = new char[size + 1];
strcpy(str, other.str);
cout<<"拷贝赋值"<<endl;
}
return *this;
}
//析构函数
~myString()
{
delete[] str;
cout<<"析构"<<endl;
}
//判空函数
void empty()
{
if(size == 0)
{cout<<"空"<<endl;}
else
{cout<<"非空"<<endl;}
}
//size函数
void mysize()
{
cout<<"size = "<<size<<endl;
}
//c_str函数
char* c_str()
{
return str;
}
//at函数
char &at(int pos)
{
if (pos < 0 || pos >= size) {
cout<<"位置不合法"<<endl;
}
return str[pos];
}
};
int main()
{
myString s1("hello");
myString s2 = s1;
myString s3;
cout<<s1.at(4)<<endl;
cout<<s1.c_str()<<endl;
cout<<s2.at(4)<<endl;
cout<<s2.c_str()<<endl;
s2.empty();
s2.mysize();
return 0;
}