尝试制作类型转换操作员

Trying to make type conversion operator

本文关键字:类型转换 操作员      更新时间:2023-10-16

我正在尝试使我的操作员起作用(有时确实如此(,但是在输出时,我会收到垃圾。

我尝试了隐式类型的转换,在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:

答案是为两个类提供operator =