1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
|
#include <iostream>
#include <string>
#include <conio.h>
using namespace std;
class Pet
{
private:
char* name;
int age;
double weight;
public:
Pet(){ name = NULL; age = 0; weight = 0.0;}// default constructor
Pet(const char*, int, double); // argument constructor
Pet(const Pet&);
~Pet();
Pet& operator = (Pet);
//void getName()const; // read the name
//void getAge()const; // read the age
//void getWeight()const; // read weight
void getInfo() const;
void setName(char*);// set the name
void setAge(int); // set the age
void setWeight(double); // set the weight
string getLifespan();// return a string
};
Pet::Pet(const char* n, int a, double w)
{
int length = strlen(n)+1;
name = new char[length];
strcpy_s(name, length, n);
age = a;
weight = w;
}
Pet::Pet(const Pet& otherPet)
{
int length = strlen( otherPet.name )+1;
name = new char[strlen(otherPet.name)+1];
strcpy_s(name, length, otherPet.name);
age = otherPet.age;
weight = otherPet.weight;
}
Pet::~Pet()
{
delete[] name;
}
Pet& Pet::operator =(Pet otherPet)
{
delete[]name;
int length = strlen( otherPet.name )+1;
name = new char[strlen(otherPet.name)+1];
strcpy_s(name, length, otherPet.name);
age = otherPet.age;
weight = otherPet.weight;
return *this;
}
void Pet::setName(char * n)
{
delete[] name;
int length = strlen(n) + 1;
name = new char[length];
strcpy_s(name, length, n);
}
void Pet::setAge(int a)
{
age = a;
}
void Pet::setWeight(double w)
{
weight = w;
}
void Pet::getInfo() const
{
if (name != NULL)
{
cout <<"Pet Name: " << name << endl;
}
cout <<"Pet Age: " << age << endl;
cout <<"Pet Weight: " << weight << endl;
}
int main()
{
Pet p1;
Pet p2("Sparky", 1, 17.2);
Pet p3(p1);
Pet p4 = p1;
cout <<"p1 is : "; p1.getInfo(); cout << endl;
cout <<"p2 is : "; p2.getInfo(); cout << endl;
cout <<"p3 is : "; p3.getInfo(); cout << endl;
cout <<"p4 is : "; p4.getInfo(); cout << endl;
p1.setName("yayo");
cout <<"p1 is : "; p1.getInfo(); cout << endl;
cout <<"p2 is : "; p2.getInfo(); cout << endl;
cout <<"p3 is : "; p3.getInfo(); cout << endl;
cout <<"p4 is : "; p4.getInfo(); cout << endl;
p2 = p1;
cout <<"p2 is: "; p2.getInfo();
_getch();
return 0;
}
|