C++ Premier Plus 6th edition - Programming excercise - Chapter12 - 1

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_42787086/article/details/84386835

Cow.h

#ifndef COW_H_
#define COW_H_

class Cow
{
    char name[20];
    char * hobby;
    double weight;
public:
    Cow();
    Cow(const char * nm, const char * ho, double wt);
    Cow(const Cow& c);
    ~Cow();
    Cow & operator=(const Cow & c);
    void ShowCow() const; // display all cow data
};

#endif

Cow.cpp

#include<iostream>
#include"cow.h"

using std::cout;

// default constructor
Cow::Cow()
{
    name[0] = '\0';
    hobby = nullptr;
    weight = 0;
}

// constructor
Cow::Cow(const char * nm, const char * ho, double wt)
{
    strcpy_s(name, strlen(nm) + 1, nm);

    // use new
    int len = strlen(ho) + 1;
    hobby = new char[len];
    strcpy_s(hobby, len, ho);

    weight = wt;
}

// copy constructor
Cow::Cow(const Cow& c)
{
    strcpy_s(name, strlen(c.name) + 1, c.name);

    // need deep copy
    int len = strlen(c.hobby) + 1;
    hobby = new char[len];
    strcpy_s(hobby, len, c.hobby);

    weight = c.weight;
}

Cow::~Cow()
{
    delete[]hobby;
}

Cow& Cow::operator=(const Cow & c)
{
    strcpy_s(name, strlen(c.name) + 1, c.name);

    // deep copy
    if (hobby == c.hobby)
        return *this;
    /*
    if here was written as if (hobby = c.hobby)
    but not ==
    name was altered
    hobby was replaced and if will always return ture
    following statements will not be implented
    which means weight was not altered, will remains 0
    */


    int len = strlen(c.hobby) + 1;
    hobby = new char[len];
    strcpy_s(hobby, len, c.hobby);

    weight = c.weight;
    return *this;
}

void Cow::ShowCow() const
{
    // whether can display char array this way is not sure
    for (int i = 0; i < strlen(name); i++)
        cout << name[i];
    cout << '\n';
    for (int i = 0; i < strlen(hobby); i++)
        cout << hobby[i];
    cout << '\n';
    cout << "Weight is: " << weight << '\n';
}
// display all cow data

main.cpp

// main()
#include<iostream>
#include"cow.h"

using std::cout;

int main()
{
    // use default constructor
    Cow first;

    // use constructor
    Cow second("name_1", "hobby_1", 10);
    cout << "Created a new object \"second\" with given char*:\n";
    second.ShowCow();

    // use copy constructor
    Cow third = second;
    cout << "\nCreated a new object \"third\" using copy constrctor, assign \"second\" to it: \n";
    third.ShowCow();

    // use operator=
    first = third;
    cout << "\nUsing reloaded \"operator=\" to assign \"third\"to \"first\": \n";
    first.ShowCow();

    std::cin.get();
}

猜你喜欢

转载自blog.csdn.net/weixin_42787086/article/details/84386835