假设我有这门课:
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]|我做错了什么,最好的方法是什么?
发布于 2013-09-23 02:11:30
搞定
T * copy() { return new T(*static_cast<T*>(this)); }在Food<T>::copy中,'this‘是Food<T>*,而您需要一个T*。
https://stackoverflow.com/questions/18950789
复制相似问题