如何在其指针中调用类的方法?

时间:2019-09-17 20:44:28

标签: c++ class

我将一个类存储在指针的一个向量中(例如一个指针),但没有语法来调用其方法。

我尝试过这样的事情:storedclasses [0] .itsmethod();但它返回“错误:在...中要求成员'itsmethod'的请求”(...)

class Bulb {
    public:
        class Leaf {
            public:
                void readval() {
                    cout << a << ", " << b << ", " << c << endl;
                }
            private:
                float a[3]={0.0};
                float b[3]={0.0};
                float c[3]={0.0};
        };
        void createLeaf(){
            Leaf * leaf = new Leaf();
            leaflist.push_back(leaf);
            cout << "It's okay :-)" << endl;
            //what my compiler hates :
            leaflist[1].readval();
        }
    private:
        vector<Leaf*> leaflist;
};

int main(void) {
    Bulb bulb; bulb.createLeaf();
}

1 个答案:

答案 0 :(得分:3)

leaflist[0]->readval();

在C,C ++,Java和大多数其他非脚本语言中,数组从0开始,而不是1,包括向量之类的容器类。因此,数组不是从1开始,而是0。

并且由于您持有指针,因此需要取消引用指针。 leaflist [0]拥有一个指针,然后使用->取消引用它。

相关问题