C++ 通过[]运算符返回向量元素引用

C++ 通过[]运算符返回向量元素引用,c++,pointers,vector,C++,Pointers,Vector,我有一个类或结构,比如说容器,具有以下结构: template <typename type> struct Container { vector <type *> v; ... functions ... type* operator[] (int i) { // not sure about this return (v)[i]; } }; 其中,函数是类型类的成员; 这就像预期的一样;然而,它可以

我有一个类或结构,比如说容器,具有以下结构:

template <typename type> struct Container {
    vector <type *> v;
    ...
    functions
    ...
    type* operator[] (int i) { // not sure about this
          return (v)[i];
    }
};
其中,函数是类型类的成员; 这就像预期的一样;然而,它可以简化为

c[0]->function()
因为我定义的[]操作符将返回指向所包含类的指针,而不是容器本身,但是编译器仍然抱怨容器类没有调用函数的成员。 这不是一个大问题,使用不同的语法可以很容易地避免,但让我觉得我对指针和引用的工作原理有一些基本的误解。 在这里定义[]运算符的正确方法是什么?我缺少什么? 先谢谢你

编辑:我编辑了问题以反映我的实际代码

您的操作员[]似乎很好。您的结构名称后面似乎缺少一个分号


对。编译器告诉我容器没有成员函数,没有类型

您当时是否为容器定义了一个函数

下面是一个编译工作示例:

#include <iostream>
#include <vector>

struct A
{
    void Function () {
        std::cout << "A::Function()" "\n" ;
    }
};

template <typename type> struct Container {
    std::vector <type *> v;

    void Function () {
        std::cout << "Container::Function ()" "\n" ;
    }

    type* operator[] (int i) { 
          return (v)[i];
    }
};

int main (void)
{
    A a ;

    Container <A> c ;

    c.Function () ;

    c.v.push_back (&a) ;
    c[0]->Function () ;

    return 0 ;
}
输出:

容器::函数 A::函数

更新

下面是一个使用指针的示例

int main (void)
{
    A a ;

    Container <A> *pC = new Container <A> ;

    pC->Function () ;

    pC->v.push_back (&a) ;
    (*pC) [0]->Function () ;

    delete pC ;

    return 0 ;
}

当然,您不应该使用这样的原始指针。您可以改为使用,也可以将内存封装到一个类中。

它应该可以工作。你能展示让编译器抱怨c[0]->函数的代码吗?c[0]->函数。“type”是否有名为function的函数?若并没有,那个么编译器正在做它的工作。是的。编译器告诉我容器没有成员函数,没有类型。谢谢。您的代码工作得非常好,并且让我注意到编译器只有在初始化指向容器的指针时才会抱怨。容器c工作,但容器*c不工作。我仍然不明白为什么会发生这种情况。@user3556781请查看我答案中的更新。输出是一样的,非常完美。我也会听从你的建议,从智能指针开始。感谢you@user3556781-请注意,如果对象为常量,则运算符[]将不起作用。您需要第二个重载运算符[]来处理常量对象。@PaulMcKenzie说得好,我本想在答案中的某个地方链接,但忘了链接。
#include <iostream>
#include <vector>

struct A
{
    void Function () {
        std::cout << "A::Function()" "\n" ;
    }
};

template <typename type> struct Container {
    std::vector <type *> v;

    void Function () {
        std::cout << "Container::Function ()" "\n" ;
    }

    type* operator[] (int i) { 
          return (v)[i];
    }
};

int main (void)
{
    A a ;

    Container <A> c ;

    c.Function () ;

    c.v.push_back (&a) ;
    c[0]->Function () ;

    return 0 ;
}
int main (void)
{
    A a ;

    Container <A> *pC = new Container <A> ;

    pC->Function () ;

    pC->v.push_back (&a) ;
    (*pC) [0]->Function () ;

    delete pC ;

    return 0 ;
}