简体   繁体   中英

How to get struct that is inside the class?

Let say I have class

class A{
public:
    struct stuff{
        int x;  
        int y;
    }; 
    stuff get_stuff(int index){
       if(index < vec_stuff.size() && index >= 0) return vec_stuff[index];
       else return nullptr;
    }
    std::vector<stuff> vec_stuff;
};

Assume I populate those vec_stuff appropriately.

Then In some other class

#inclde "A.h"
class B{
public:
     B(){}

     void f(int index, int k){

        xxxx =  a.get_stuff(index) 
     }

    A a; // assume A is initialized properly
}

So in the place where I wrote xxxx there it should be struct stuff but when I do this I get use of undeclared identifier So how do I make compiler know that stuff I am referring is inside of A.

You can either specify the fully qualified name by using the scope-operator:

A::stuff xxx = a.get_stuff(index);

Or if your compiler supports C++11 or later you can use the auto keyword and let the compiler figure out the type:

auto xxx = a.get_stuff(index);

As a side note:

Your get_stuff method shouldn't even compile since it's trying to return a stuff object, nullptr is not a stuff object.

stuff get_stuff(int index){
   if(index < vec_stuff.size() && index >= 0) return vec_stuff[index];
   else return nullptr;
}

If it's expected to have a value and thus it's an exceptional case, then you should throw an exception. Otherwise you can let it return a stuff* and just do return &vec_stuff[index] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM