【发布时间】:2015-03-22 10:18:22
【问题描述】:
对不起,如果这是一个如此简单的问题,一定有一些我不明白的关于继承的东西,c++ 中的virtual 和override。在下面的示例中,我得到了一个与我特意覆盖的虚拟方法相关的编译时错误,以避免在子类中出现此类错误。难道我做错了什么?
#include <array>
#include <deque>
template <class T, class C>
struct foo
{
virtual const C& data() const =0;
inline virtual T& operator[] ( unsigned n ) const
{ return const_cast<T&>( data()[n] ); }
};
/**
* The implementation of foo::operator[] is useful for classes inheriting
* with simple sequence containers like:
* foo<T,std::deque<T>>, foo<T,std::vector<T>>, ..
*
* But the following requires operator[] to be redefined:
*/
template <class T, unsigned N>
struct baz
: public foo<T, std::deque<std::array<T,N>> >
{
typedef std::deque<std::array<T,N>> data_type;
data_type m_data;
inline const data_type& data() const
{ return m_data; }
inline virtual T& operator[] ( unsigned n ) const override
{ return const_cast<T&>( data()[n/N][n%N] ); }
};
int main()
{
baz<double,3> b; // throws an error relative to foo::operator[] depsite override
}
EDIT 1错误:
clang++ -std=c++0x -Wall virtual_operator.cpp -o virtual_operator.o
virtual_operator.cpp:11:12: error: const_cast from 'const value_type' (aka 'const std::__1::array<double, 3>') to 'double &' is not allowed
{ return const_cast<T&>( data()[n] ); }
^~~~~~~~~~~~~~~~~~~~~~~~~~~
virtual_operator.cpp:26:8: note: in instantiation of member function 'foo<double, std::__1::deque<std::__1::array<double, 3>, std::__1::allocator<std::__1::array<double, 3> > > >::operator[]'
requested here
struct baz
^
1 error generated.
EDIT 2 我认为这是问题的一部分;如果编译失败是因为foo::operator[] 仍然可以在baz 中调用,那么如果我不将foo::operator[] 声明为虚拟(即隐藏而不是覆盖),为什么它编译得很好? p>
【问题讨论】:
-
您能否将错误本身添加到问题中?
-
@JosephMansfield 查看编辑
-
bar是否与问题相关?我认为它只会增加噪音并使其更难阅读。你应该删除它。 -
@Angew 这更好吗?
-
当然。读者解析和突出问题区域的模板代码减少了 33%。如果我还没有这样做,我当然会赞成:-)
标签: c++ inheritance c++11 polymorphism overriding