#include <iostream>
using namespace std;
class Person
{
const string name;
int age;
char sex;
public:
Person():name("lisi")
{cout << "Person无参构造" << endl;}
Person(string name,int age,char sex):name(name),age(age),sex(sex)
{cout << "Person有参构造" << endl;}
void show()
{
cout <<"person的show:"<< name << age << sex <<endl;
}
Person(const Person &other):name(other.name)
{
this->age = other.age;
this->sex=other.sex;
cout << "Person的拷贝构造函数" << endl;
}
Person &operator=(const Person &other)
{
if(&other!=this)
{
string name=other.name;
this->age=other.age;
this->sex=other.sex;
cout << "Person的拷贝赋值函数" << endl;
}
return *this;
}
};
class Stu
{
Person p1;
double *pd;
public:
Stu():pd(new double)
{cout << "Stu的无参构造" << endl;}
Stu(string name,int age,char sex,double score):p1(name,age,sex),pd(new double(score))
{cout << "Stu有参构造" << endl;}
void show()
{
p1.show();
cout << *pd <<endl;
}
Stu(const Stu &other):p1(other.p1)
{
this->pd=other.pd;
}
Stu &operator=(const Stu &other)
{
if(&other!=this)
{
this->p1=other.p1;
*(this->pd)=*(other.pd);
cout << "Stu的拷贝赋值函数" << endl;
}
return *this;
}
};
int main()
{
Person p2("wangwu",20,'n');
p2.show();
Person p3=p2;
p3.show();
Person p4;
p4=p2;
p4.show();
Stu s2("zhangsan",20,'n',99.2);
s2.show();
Stu s3=s2;
s3.show();
Stu s4;
s4=s2;
s4.show();
return 0;
}
#include <iostream>
#include <cstring>
using namespace std;
using namespace std;
class myString
{
private:
char *str; //变化c风格的字符串
int size; //记录字符串的实际长度
public:
//无参构造
myString() : str(new char), 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) {
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;
}