English 中文(简体)
继承与争论无关的职能
原标题:Function overriding with argument inheritance

我有一个通用的项目清单类别,以制作一个更具体的清单,将清单作为基类,例如这样。

ref class ItemBase { }
ref class ItemA : ItemBase { }
ref class ItemList abstract {
 public:
  virtual void add(ItemBase ^p);
}
ref class ItemListA : ItemList {
 public:
  virtual void add(ItemA ^p) override; // it doesn t works :(
}

我想限制在每个类别中增加特定类型的物品。

最佳回答

这样做的公认模式是使基类方法<编码>受保护<>/代码>:

ref class ItemBase { }
ref class ItemA : ItemBase { }
ref class ItemList abstract {
 protected:
  virtual void addInternal(ItemBase ^p);
}
ref class ItemListA : ItemList {
 public:
  virtual void add(ItemA ^p){addInternal(p);} 
}

这里是使用通用物的更好解决办法。 说明我们如何限制一般参数<代码>T至ItemBase,以强制规定这种收集必须只用。 项目Base或其子类。

ref class ItemBase { };
ref class ItemA : public ItemBase { };

generic <class T>
where T: ItemBase
ref class ItemList abstract {
 public:
     virtual void Add(T p){}
};

ref class ItemListA : ItemList<ItemA^> {
   //no need to override Add here
};

//usage
int main(array<System::String ^> ^args)
{
    ItemListA^ list = gcnew ItemListA();
    list->Add(gcnew ItemA());
}
问题回答

暂无回答




相关问题
Subclass check, is operator or enum check

A couple of friends was discussing the use of inheritance and how to check if a subclass is of a specific type and we decided to post it here on Stack. The debate was about if you should implement a ...

C++ Class Inheritance problem

Hi I have two classes, one called Instruction, one called LDI which inherits from instruction class. class Instruction{ protected: string name; int value; public: Instruction(string ...

Overloading a method in a subclass in C++

Suppose I have some code like this: class Base { public: virtual int Foo(int) = 0; }; class Derived : public Base { public: int Foo(int); virtual double Foo(double) = 0; }; ...

Embedding instead of inheritance in Go

What is your opinion of this design decision? What advantages does it have and what disadvantages? Links: Embedding description

Extending Flex FileReference class to contain another property

I want to extend the FileReference class of Flex to contain a custom property. I want to do this because AS3 doesn t let me pass arguments to functions through event listeners, which makes me feel sad,...

Interface Inheritance in C++

I have the following class structure: class InterfaceA { virtual void methodA =0; } class ClassA : public InterfaceA { void methodA(); } class InterfaceB : public InterfaceA { virtual ...

热门标签