1

假设我有这个课程:

class Food
{
public:
    Food * copy() const
    {
        return new Food(*this);
    }
    .
    .
    .
};

我希望它成为继承该copy方法的其他类的基类。我每次都必须手动编写它:

class Cheese: public Food
{
public:
    Cheese * copy() const
    {
        return new Cheese(*this);
    }
    .
    .
    .
};

class Bread: public Food
{
public:
    Bread * copy() const
    {
        return new Bread(*this);
    }
    .
    .
    .
};

等如何解决这个问题?我正在考虑模板,但我仍然不确定如何使用它们......这是我制作的程序,它不会编译:

#include <cstring>

template <class T>

class Food
{
protected:
    double weight;
public:
    T * copy() { return new T(*this); }
    Food(){ weight = 1; }
    Food(const Food& f){ weight = f.weight; }
};

class Cheese : public Food<Cheese>
{
    char * color;
public:
    Cheese(const char * c)
    {
        color = new char[strlen(c)+1];
        strcpy(color,c);
    }
    Cheese(const Cheese& c)
    {
        weight = c.weight;
        color = new char[strlen(c.color)+1];
        strcpy(color,c.color);
    }
};

main()
{
    Cheese first("yellow");
    Cheese * second = first.copy();
}

以下是错误:

|10|error: no matching function for call to ‘Cheese::Cheese(Food<Cheese>&)’|
|10|note: candidates are:|
|24|note: Cheese::Cheese(const Cheese&)|
|24|note:   no known conversion for argument 1 from ‘Food<Cheese>’ to ‘const Cheese&’|
|19|note: Cheese::Cheese(const char*)|
|19|note:   no known conversion for argument 1 from ‘Food<Cheese>’ to ‘const char*’|
||In member function ‘T* Food<T>::copy() [with T = Cheese]’:|
|10|warning: control reaches end of non-void function [-Wreturn-type]|

我做错了什么,实现这一目标的最佳方法是什么?

4

1 回答 1

3

做了

T * copy() { return new T(*static_cast<T*>(this)); }

Food<T>::copy'this' 中Food<T>*,你需要一个T*.

于 2013-09-23T02:11:30.103 回答