试图使类型转换运算符

时间:2019-05-23 14:43:52

标签: c++ class types

我试图使我的操作员工作(有时确实如此),但在输出上我收到了一个垃圾。

我尝试了隐式类型转换,并在IndProd构造函数中通过设置器设置对象f的私有方法,无济于事。

class FoodProd : public Exp
{
    private:
        int consump_term;
        char *producer;
    public:
        FoodProd()
        {
            producer = new char[7];
            strcpy(producer, "NONAME");
            consump_term = 0;
        }
        FoodProd(int term, char *str)
        {
            int size1 = strlen(str) + 1;
            producer = new char[size1];
            if (producer)
                strcpy(producer, str);
            consump_term = term;
        }
        FoodProd(const FoodProd &food)
        {
            producer = new char[strlen(food.producer) + 1];
            strcpy(producer, food.producer);
            consump_term = food.consump_term;
        }
        ~FoodProd()
        {
            if (producer)
                delete[] producer;
        }
...
}

class IndProd : public Exp
{
    private:
        char *category;
        int price;
        char *manufacturer;
    public:
        IndProd()
        {
            category = new char[7];
            strcpy(category, "NONAME");
            manufacturer = new char[7];
            strcpy(manufacturer, "NONAME");
            price = 0;
        }
        IndProd(char *cat, int pr, char *manuf)
        {
            category = new char[strlen(cat) + 1];
            strcpy(category, cat);
            price = pr;
            manufacturer = new char[strlen(manuf) + 1];
            strcpy(manufacturer, manuf);
        }
        IndProd(const IndProd &ind)
        {
            category = new char(strlen(ind.category) + 1);
            strcpy(category, ind.category);
            price = ind.price;
            manufacturer = new char(strlen(ind.manufacturer) + 1);
            strcpy(manufacturer, ind.manufacturer);
        }
        ~IndProd()
        {
            if (category)
                delete[] category;
            if (manufacturer)
                delete[] manufacturer;
        }
        IndProd (FoodProd obj)
        {
            category = new char[7];
            strcpy(category, "NONAME");
            manufacturer = new char[strlen(obj.get_producer()) + 1];
            strcpy(manufacturer, obj.get_producer());
            price = 0;
        }
        operator FoodProd const ()
        {
            FoodProd f(0, manufacturer);
            return f;
        }
}

Input:

FoodProd FP(20, "Ukraine");
IndProd ID("BudMat", 1900, "Germany");
FoodProd FP2;
FP2 = ID;
FP2.print();
IndProd ID2;
ID2 = FP;

Output:

Term of consumption: 0 days.
Manufacturer: ↑r;

Category: ♫      Price: 0$
Manufacturer:

1 个答案:

答案 0 :(得分:0)

答案是为两个类都提供operator =