C++一些构造,老是忘记
**
**
// work05_01.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
//(重点掌握)给出学生类的声明如下:
class Student
{
public:
enum Gender { Male, Female }; //枚举类型,性别
//声明友元函数,用于将枚举类型输出文本形式
friend std::ostream& operator<<(std::ostream& os, Gender gender);//友元函数要在class外定义
Student() //无参数构造函数
{
name_ = NULL;
gender_ = Male;
}
Student(const char* name, Gender gender) //带参数构造函数
{
name_ = new char[strlen(name)+1];
strcpy_s(name_,strlen(name)+1,name);
gender_ = gender;
}
Student(const Student& student) //拷贝构造函数
{
name_ = new char[strlen(student.name_)+1];
strcpy_s(name_, strlen(student.name_)+1,student.name_);
}
Student& operator= (const Student& student) //赋值运算符
{
if (this == &student)
{
return *this;
}
delete[] name_;
name_ = new char[strlen(student.name_) + 1];
strcpy_s(name_, strlen(student.name_) + 1, student.name_);
}
~Student() //析构函数,释放内存
{
if (name_ != NULL) {
delete[] name_;
}
}
void Show() const //常成员函数用于显示学生姓名和性别
{
std::cout << "名字:" << name_ << "\n性别:" << gender_ << "\n\n";
}
private:
char* name_; //名字
Gender gender_; //性别
};
std::ostream& operator<<(std::ostream& os, Student::Gender gender)
{
if (gender == Student::Female)
{
os << "Female";
}
else {
os << "Male";
}
return os;
}
//完成学生类的实现,并利用下面给出的main函数测试所有的成员函数。(可以尝试在常成员函数中修改成员数据,观察编译器是否报错)。
int main()
{
Student s1;
Student s2("Nicolas ZhaoSi", Student::Gender::Male);
Student s3("Jason GuoDa Statham", Student::Gender::Male);
Student s4(s2);
s1 = s3;
s1.Show();
s2.Show();
s3.Show();
s4.Show();
}