2017-03-03 37 views
1

让说我有类如何获得类内的结构?

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; 
}; 

假设我适当地填充这些vec_stuff

然后在其他一些类

#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 
} 

所以在我写xxxx那里应该是struct stuff的地方,但我这样做的时候,我得到use of undeclared identifier那么,如何让编译器知道stuff我指的是A.内部

+5

'else return nullptr;'HUH ?? –

+5

'auto'? ------- – Quentin

+1

@WhiZTiM或'auto xxxx = a.get_stuff(index);'。即使使用'private'嵌套结构,这也有利于工作。 –

回答

6

您可以通过使用范围,运营商指定的全名:

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

或者,如果你的编译器支持C++ 11或更高版本可以使用关键字auto,让编译器弄清楚类型:

auto xxx = a.get_stuff(index); 

补充说明:

get_stuff方法应该不会编译,因为它试图返回一个stuff对象,而nullptr不是一个stuff对象。

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

如果预计有一个值,因此它是一个例外,那么你应该抛出一个异常。否则,你可以让它返回一个stuff*,只是返回&vec_stuff[index]

+0

关于'return nullptr'所以我应该只抛出异常呢? – pokche

+0

@pokche取决于你的用例。如果预期有价值,那么这是一个*例外情况,那么你应该。否则,你可以让它返回一个'stuff *',然后返回'&vec_stuff [index];' –

+2

@GillBates:或者一个“可选”包装器。坦白地说,抛出一个异常是一个合理的,简单明了的方法,无论咒语 –