Wei Han Chi
Wei Han Chi

Reputation: 19

getting private inner class into main

here's the code:

class Vec
{
public:
    Vec() {len=0;};
    Vec(int n);
    ~Vec();
    void setValue(int idx,int v);
    void printVec() const;
private:
    class Items
    {
        friend class Vec;
        Items(){value = 0;};
        Items(int v){value = v;};
        int value;
    };
    int len;
    Items *vec;
};

/*Declare the member functions & constructor & destructor*/

int main()
{
    Vec vector(5);
    vector.printVec();
    for(int i=0;i<5;i++){
        vector.setValue(i,i);
        vector.printVec();
    }
    Items n;
    return 0;
}

When I try to use Items n; , I get an error: "Items undeclared".

But when using vector.Items n; , still the error is "invalid use of class Vec::Items"

How can I get the compiler to recognize the declaration?

Upvotes: 2

Views: 111

Answers (1)

Jason
Jason

Reputation: 32490

I wanna make it can be declared.

You need to make Items a public nested or inner-class of the Vec class, and then use the scope-resolution operator (i.e., Vec::Items) when creating an instance of that object-type. Otherwise you can only create an instance of a Vec::Items object inside a method of Vec since it would be a private inner-class of Vec, and not a class-type that is publicly accessible.

Upvotes: 2

Related Questions