#include<iostream>
using namespace std;
enum color { White, Black, Red, Brown, Green };
class Automobile
{
private:
    char *model;
    color c;
    int price;
    double mileage;
    static int countC;
public:
    Automobile(const char *model, color c, int price, double mileage);
    ~Automobile();
    void Assign(Automobile & p);
    void display();
    static int getCount();
    friend bool Mileage(Automobile &p);
};
Automobile::Automobile(const char *model, color c, int price, double mileage)
{
    this->model = new char[strlen(model) + 1];
    strcpy_s(this->model, strlen(model) + 1, model);
    this->c = c;
    this->price = price;
    this->mileage = mileage;
    ++countC;
    cout << "构造函数:" << model << "\n";
}
Automobile::~Automobile()
{
    cout << "析构函数:" << model << "\n";
    delete model;
    --countC;
}
void Automobile::Assign(Automobile & p)
{
    this->model = new char[strlen(p.model) + 1];
    strcpy_s(this->model, strlen(p.model) + 1, p.model);
    this->c = p.c;
    this->price = p.price;
    this->mileage = p.mileage;
}
int Automobile::getCount()
{
    return countC;
}
void Automobile::display()
{
    const char *cl=0;
    switch (c)
    {
    case 0:cl = "White"; break;
    case 1:cl = "Black"; break;
    case 2:cl = "Red"; break;
    case 3:cl = "Brown"; break;
    case 4:cl = "Green"; break;
    }
    cout << "\t该汽车型号:" << model << "\n";
    cout << "\t颜色:" << cl << "\n";
    cout << "\t价格:" << price << "\n";
    cout << "\t里程:" << mileage << "\n";
}
bool Mileage(Automobile &p)
{
    if (p.mileage >= 1000)
        return true;
    else
        return false;
}
int Automobile::countC = 0;
void main()
{
    cout << "当前汽车数量:" << Automobile::getCount() << "\n";
    Automobile c1[3] = { Automobile("A1",White,100000,371.5),
                                   Automobile("A3",Red,150000,951.4),
                                      Automobile("A5",Black,200000,1024.1) };
    cout << "当前汽车数量:" << Automobile::getCount() << "\n";
    Automobile *c2 = &c1[1];
    cout << "当前汽车数量:" << Automobile::getCount() << "\n";
    Automobile *c3 = new Automobile("A7", Green, 25, 747);
    cout << "当前汽车数量:" << Automobile::getCount() << "\n";
    c3->Assign(c1[2]);
    c3->display();
    cout <<"如果里程大于1000为1(真),否则为0(假):"<< Mileage(*c3) << "\n";
    delete c3;
    system("pause");
}
Last modification:December 4th, 2018 at 11:57 pm
如果觉得我的文章对您有帮助,请随意赞赏:)