【问题标题】:error: 'operator[]' is not defined错误:未定义“操作员 []”
【发布时间】: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


    【解决方案1】:

    由于你没有说出你真正的设计目标是什么,所以提出好的东西有点困难,但至少要使用

    template<class CC> friend X<CC,B>& X<A,B>::operator[]( const CC& );
    

    因为朋友声明将使它编译,因为这告诉它是一个模板。

    编辑:

    再想一想,我认为您的代码也应该可以工作,因为它没有指定专业化。您是否尝试过使用 clang 进行测试?这似乎是 gcc 中的一个错误......

    【讨论】:

    • 是的,可以。它将每个类 operator[] 声明为友元,但这并不重要。设计目标是创建一个库,用于在内存中存储表达式并仅在需要时对不同的输入进行计算。支持的运算符之一是 operator[],但它不能编译。我尝试了您的建议,现在可以正常编译了。
    • VC++2010无法编译
    • 我没试过,但我也是这么想的。我将尝试 clang,如果它编译,那么我将报告 gcc 上的错误。
    猜你喜欢
    • 1970-01-01
    • 2018-01-06
    • 2022-07-26
    • 1970-01-01
    • 2013-11-02
    • 2021-08-10
    • 2015-06-04
    • 1970-01-01
    • 2020-11-06
    相关资源
    最近更新 更多