c++十二章第一题

#ifndef COW_H_
#define COW_H_
class Cow {
    
    
private:
    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;
};
#endif
#include <iostream>
#include <cstring>
#include "cow.h"
#pragma warning(disable:4996) //这里是关键,没有的话会出现4996警告
Cow::Cow()
{
    
    
    name[0] = '\0';
    hobby = new char[1];
    hobby[0] = '\0';
    weight = 0;
}
Cow::Cow(const char* nm, const char* ho, double wt)
{
    
    
    strcpy(name, nm);   //4996
    int len;
    len = std::strlen(ho);
    hobby = new char[len + 1];
    strcpy(hobby, ho);  //4996
    weight = wt;
}
Cow::Cow(const Cow& c)
{
    
    
    std::strcpy(name, c.name);//4996
    int len;
    len = std::strlen(c.hobby);
    hobby = new char[len + 1];
    weight = c.weight;
}
Cow::~Cow()
{
    
    
    delete[] hobby;
    std::cout << "byb!\n";
}
Cow& Cow::operator=(const Cow& c)
{
    
    
    int len;
    if (this == &c)
        return *this;
    delete[] hobby;
    weight = c.weight;
    len = std::strlen(c.name);
    hobby = new char[len + 1];
    std::strcpy(hobby, c.hobby);  //4996
    std::strcpy(name, c.name);  //4996
    return *this;
}
void Cow::ShowCow() const
{
    
    
    std::cout << "name: " << name << std::endl;
    std::cout << "hobby: " << hobby << std::endl;
    std::cout << "weight: " << weight << std::endl;
}
#include <iostream>
#include <cstring>
#include <string>
#include "cow.h"
int main()
{
    
    
    using std::cout;
    using std::endl;
    Cow hand1;
    hand1.ShowCow();
    Cow hand2("chen kai1", "programmer", 200.34);
    hand2.ShowCow();
    Cow hand3("wang s", "a dan b", 170.72);
    hand3.ShowCow();
    cout << "transler; \n";
    hand2=hand3;
    hand2.ShowCow();
    hand3.ShowCow();
    return 0;
}

猜你喜欢

转载自blog.csdn.net/wode_0828/article/details/108624044