C++ day3 (类的构造函数重载)

 

 

 作业:

  1. 有以下类定义,写出该类的构造函数,析构函数,拷贝构造函数,要求,构造函数要创建出长度为10的字符串给name用,所有类对象的空间都是用new动态申请。

class Stu {

string name;

int age; i

nt score;

int *high;

};

#include 
#include 
using namespace std;

class Stu
{
public:
    string name;
    int age;
    int score;
    int *high;
public:
    //无参构造
    Stu ()
    {
        
        //  int *my_score = &this->score; 
        //  my_score=new int;
        
        this->high = new int;
        this->name = new char[10];
        cout << "无参构造" << endl;
    }
    //析构函数
    ~Stu()
    {
        cout << "调用析构函数" << endl;
        delete high;
        delete &name;

    }
    //拷贝函数
    Stu (Stu &a):name(a.name),age(a.age),score(a.score)
    {
        cout << "调用拷贝函数" << endl;
        this->high = new int;
        memcpy(this->high,a.high,sizeof(*(a.high)));
    }
    void show();
  };

void Stu::show()
{
    cout << "姓名 :" << name << endl;
    cout << "年龄 :" << age << endl;
    cout << "分数 :" << score << endl;
    cout << "身高 :" << *high << endl;

}

int main()
{
    cout << "Hello World!" << endl;
    Stu student1;
    student1.age=18;
    *student1.high=178;
    student1.name="小明";
    student1.score=98;
    student1.show();
    Stu student2=student1;
    student2.show();

    return 0;
}

你可能感兴趣的:(C++,c++,java,数学建模)