定义一个Person类,有const修饰的成员name;int成员age,char类型的成员sex,定义一个Stu类,包含Person 成员,double *成员,要求:写出Person和Stu的构造和析构函数,每个类至少写出两种构造函数,实现一个公有的show函数,输出Stu类中属性和Person类中属性的值。在上一个练习的基础上,写出Person类和Stu类的拷贝构造函数。完成拷贝赋值函数
#include <iostream>
using namespace std;
class Person
{
const string name;
int age;
char sex;
public:
Person():name("zhangsan")
{}
Person(string name,int age,char sex):name(name),age(age),sex(sex)
{}
~Person()
{}
void show()
{
cout << name << endl;
cout << age << endl;
cout << sex << endl;
}
Person(const Person &other):name(other.name),age(other.age),sex(other.sex)
{}
Person &operator=(const Person &other)
{
if(&other != this)
{
this->age = other.age;
this->sex = other.sex;
}
}
};
class Stu
{
Person p1;
double *pd;
public:
Stu():pd(new double)
{}
Stu(string name,int age,char sex,double score):p1(name,age,sex),pd(new double(score))
{}
~Stu()
{
cout << "z准备释放空间:" << pd << endl;
delete pd;
cout << "Stu的析构函数" << endl;
}
void show()
{
p1.show(); //通过Person类型的p1成员,调用Person中的show函数
cout << "Stu中的show:" << *pd << endl;
}
//实现Stu的拷贝构造,调用其他类的拷贝构造函数时,也需要传同类引用
Stu(const Stu &other):pd(new double(*(other.pd))),p1(other.p1)
{}
Stu &operator=(const Stu &other)
{
if(&other != this)
{
*(this->pd) = *(other.pd);
this->p1 = other.p1;
}
}
};
int main()
{
Stu s2("zhangsan",20,'m',23.9);
s2.show();
Stu s3 ;
s3 = s2;
s3.show();
return 0;
}
#include <iostream>
#include <cstring>
using namespace std;
class myString
{
private:
char *str; //记录c风格的字符串
int size; //记录字符串的实际长度
public:
//无参构造
myString():str(new char [64]())
{}
//有参构造
myString(char *str):str(new char [64]())
{
strcpy(this->str,str);
size=mysize();
}
//拷贝构造
myString(const myString &other):str(new char [64]()),size(other.size)
{
strcpy(this->str,other.str);
}
//拷贝赋值函数
myString &operator=(const myString &other)
{
if(&other != this)
{
this->size = other.size;
strcpy(this->str,other.str);
}
return *this;
}
//析构函数
~myString()
{
delete [] str;
}
//判空函数
int empty()
{
if(str==nullptr&&size==0)
{
return 1;
}
return 0;
}
//size函数
int mysize()
{ int i=0;
for( i=0;str[i]!='\0';i++);
return i;
}
//c_str函数
char* c_str()
{
return str;
}
//at函数
char &at(int pos)
{
if(pos<mysize()&&pos>=0)
{
int i=0;
return str[pos];
}
cout << "pos参数错误没有该值" << endl;
};
};
int main()
{
myString s1("hello");
cout << "empty " << s1.empty() << endl;
cout << "at " << s1.at(1) << endl;
cout << "at " << s1.at(4) << endl;
cout << "size " << s1.mysize() << endl;
cout << "c_str " << s1.c_str() << endl;
myString s2 = s1;
cout << "copy构造" << s2.c_str() << endl;
myString s3;
s3 = s1;
cout << "copy赋值"<< s3.c_str() << endl;
return 0;
}