我试图了解Mixin概念,但我似乎无法理解它是什么.我看待它的方式是,它是一种通过使用继承来扩展类的功能的方法.我读过人们将它们称为"抽象子类".有谁能解释为什么?
如果您根据以下示例(从我的一个演讲幻灯片中)解释您的答案,我将不胜感激:
我需要拆分一个类(.h文件)
#ifndef _L_H
#define _L_H
template<class L> class Myclass{
public:
L();
firstoperator(..);
secondoperator(..);
private:
...
}
template <class L> Myclass<L>::L() ...
template <class L> Myclass<L>::firstoperator(..) ...
template <class L> Myclass<L>::secondoperator(..) ...
Run Code Online (Sandbox Code Playgroud)
在两个不同的.h文件中,格式如下:
#ifndef _L_H
#define _L_H
template<class L> class Myclass{
public:
L();
firstoperator(..);
private:
...
}
template <class L> Myclass<L>::L() ...
template <class L> Myclass<L>::firstoperator(..) ...
Run Code Online (Sandbox Code Playgroud)
#ifndef _L_H
#define _L_H
template<class L> class Myclass{
public:
secondoperator(..);
}
template <class L> Myclass<L>::secondoperator(..) ...
Run Code Online (Sandbox Code Playgroud)
如何在没有冲突的情况下正确完成?
先感谢您.
比方说,我有两个派生自抽象基类的类Ingredient
.现在,Carrot
并Potato
实现纯虚函数(称之为Taste()
)的Ingredient
通过公共继承.现在,假设我想有一类Salt
就是一个Ingredient
(即,它是由它派生的),但需要调用Taste()
它的姊妹类的实现?
基本上,Salt
该类稍微修改了Taste()
其姐妹类的实现.这可以实施吗?如果是这样,怎么样?
这是我想要做的草图:
class Ingredient {
virtual void Taste() = 0;
};
class Carrot : public Ingredient {
void Taste() { printf("Tastes like carrot");}
};
class Potato : public Ingredient {
void Taste() { printf("Tastes like potato"); }
};
class Salt : public Ingredient {
void Taste() { SisterClass->Taste(); printf(" but salty"); }
};
Run Code Online (Sandbox Code Playgroud)