C++ 错误:';操作员[]和#x27;没有定义
我在用g++编译与运算符[]相关的库片段时遇到问题 我已使用此代码重新创建了相同的问题:C++ 错误:';操作员[]和#x27;没有定义,c++,templates,operator-overloading,C++,Templates,Operator Overloading,我在用g++编译与运算符[]相关的库片段时遇到问题 我已使用此代码重新创建了相同的问题: 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
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];
}
模板类X{
公众:
模板X&运算符[](常量C&);
};
模板类Y:public X{
friend X&X::模板运算符[](常量C&);
私人:
Y(X&对象,常数C&索引):X(){};
};
模板X&X::运算符[](常量C和索引){
返回*(新Y(*此,索引));
}
int main(){
X;
X&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
/src/test.cpp:在“Y”的实例化中:
./src/test.cpp:14:从“X&X::operator[](常量C&)[带C=int,A=int,B=void]实例化”
./src/test.cpp:19:从此处实例化
./src/test.cpp:8:错误:“未定义运算符[]”
./src/test.cpp:在成员函数“X&X::operator[](常量C&)[其中C=int,A=int,B=void]”中:
./src/test.cpp:19:从此处实例化
./src/test.cpp:10:error:'Y::Y(X&,const C&)[with A=int,B=void,C=int]是私有的
./src/test.cpp:14:错误:在此上下文中
我认为问题出在Y类中“operator[]”的友元声明中,但我不知道哪里错了。我试着搜索自己,但找不到任何有用的东西。
有人能帮我吗
谢谢,Gianni因为你没有说出你真正的设计目标是什么,所以提出一些好的东西有点困难,但至少使用
template<class CC> friend X<CC,B>& X<A,B>::operator[]( const CC& );
模板友元X&X::运算符[](const CC&);
因为友元声明将使它编译,因为这告诉它是一个模板
编辑:
再想一想,我认为您的代码也应该工作,因为它没有指定专门化。你试过用叮当声来测试它吗?这似乎是gcc中的一个bug…是的,这样就可以了。它将每个类运算符[]声明为朋友,但这并不重要。设计目标是创建一个库,用于将表达式存储在内存中,并仅在需要时对不同的输入进行计算。支持的运算符之一是运算符[],但它不编译。我试过你的建议,现在编译的很好。它不是用VC++2010编译的。我没有试过,但我也有同样的想法。我将尝试clang,如果它编译了,那么我将在gcc上报告一个bug。