gpt4 book ai didi

c++ - 泛型类中的多态性在 C++0x 中不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 14:32:43 25 4
gpt4 key购买 nike

基本上从 C++ FAQ 中我了解到:

A virtual function allows derived classes to replace the implementation provided by the base class. The compiler makes sure the replacement is always called whenever the object in question is actually of the derived class, even if the object is accessed by a base pointer rather than a derived pointer. This allows algorithms in the base class to be replaced in the derived class, even if users don't know about the derived class.

不过,使用模板这就变得不正确了。

我需要一个由另一个模板类派生的模板类。在那之后我发现在基模板类中有一个虚函数是没有意义的,谷歌搜索我发现有一种技术可以克服泛型编程中多态性的限制,称为类型删除。

我读过的示例和教程几乎与我的需求无关。另外我不确定我是否正确理解了类型删除的概念。作为初学者,我需要简单地做:

template <typename T>
class Foo
{
public:
virtual void doX(){cout<<"doX from Foo"<<endl;}
};

template <typename T>
class Bar : public Foo<T>
{
public:
void doX(){cout<<"doX from Bar"<<endl;}
};

还有,

Foo<int>* p;
Foo<int> i;
i.doX(); // "doX from Foo", it's ok
Bar<int> j;
j.doX(); // "doX from Bar", it's ok
p=&i;
p->doX(); // should be "doX from Foo", it's ok
p=&j;
p->doX(); // I expect "doX from Bar", but it's "doX from Foo"

编辑:我的问题是如何实现上述行为?没有模板,它按预期工作。我需要同样的普通类(class)。

简单地说,我有一个基类B。这是一个模板类。它有一个虚函数。而且我还有一个 B 的子类,它也是一个模板类,它应该重新实现 B 的一些行为(以某种方式实现 B).

EDIT2:刚刚编辑了标题。我正在使用标志 -std=c++0x 使用 g++ 4.6.3 编译器编译我的代码,因为我需要 std::threadstd::unique_ptr 在我的代码中。令人惊讶的是,删除 -std=c++0x 上面的代码按预期工作。我也试过 g++ 4.7,2011 和 2003 标准都没有问题。

最佳答案

嗯,它不会工作,因为 p 被分配给 i 指针,而 i 是 Foo 的类型。您正在使用基类函数。您应该使基类函数成为纯虚拟函数(通过在函数末尾添加 = 0)。那么它应该可以工作。

编辑:我没有注意到它被您检查为 OK,以为那是错误。我自己用 msvc 编译器尝试了代码,它确实按预期工作。

关于c++ - 泛型类中的多态性在 C++0x 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11333642/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com