【发布时间】:2011-10-29 16:38:13
【问题描述】:
我在使用 g++ 编译与 operator[] 相关的库片段时遇到问题。
我用这段代码重现了同样的问题:
template<class A,class B> class X {
public:
template<class C> X<C,B>& operator[]( const C& );
};
template<class A,class B,class C> class Y : public X<C,B> {
friend X<C,B>& X<A,B>::template operator[]<C>( const C& );
private:
Y( X<A,B>& object , const C& index ) : X<C,B>() {};
};
template<class A,class B> template<class C> X<C,B>& X<A,B>::operator[]( const C& index ) {
return *( new Y<A,B,C>( *this , index ) );
}
int main() {
X<int,void> x;
X<int,void>& y = x[2];
}
g++ 退出并出现以下错误:
./src/test.cpp: In instantiation of ‘Y<int, void, int>’:
./src/test.cpp:14: instantiated from ‘X<C, B>& X<A, B>::operator[](const C&) [with C = int, A = int, B = void]’
./src/test.cpp:19: instantiated from here
./src/test.cpp:8: error: ‘operator[]’ not defined
./src/test.cpp: In member function ‘X<C, B>& X<A, B>::operator[](const C&) [with C = int, A = int, B = void]’:
./src/test.cpp:19: instantiated from here
./src/test.cpp:10: error: ‘Y<A, B, C>::Y(X<A, B>&, const C&) [with A = int, B = void, C = int]’ is private
./src/test.cpp:14: error: within this context
我认为问题出在Y类中'operator[]'的朋友声明中,但我不知道哪里错了。我尝试搜索自己,但找不到任何有用的东西。 谁能帮帮我?
谢谢,詹尼
【问题讨论】:
标签: c++ templates operator-overloading