2010-01-29 139 views
0

我不知道如何調用它。基本上我想用嵌套成員做一個類。C++類和嵌套成員

例子:

ball->location->x; 
or 
ball->path->getPath(); 

現在我只知道如何使公共和私有成員,如

ball->x; 
ball->findPath(); 

感謝

回答

2

事情是這樣的:

class Plass 
{ 
public: 
    Plass(Point *newPoint, Way *newWay) 
    { 
     moint = newPoint; 
     bay = newWay; 
     // or instantiate here: 
     // moint = new Point(); 
     // bay = new Way(); 
     // just don't forget to mention it in destructor 
    } 
    Point *moint; 
    Way *bay; 
} 

從在這裏你可以這樣做:

Plass *doxy = new Plass(); 
doxy->moint->x; 
doxy->bay->path->getPath(); 
+0

您可以使用std :: auto_ptr,因此您不必記住刪除析構函數中的對象。 – Messa 2010-01-29 00:42:53

0

試試這個:

struct Location 
{ 
    int x; 
    int y; 
}; 

struct Path 
{ 
    std::string getPath(); 
}; 

struct Ball 
{ 
    Location location; 
    Path path; 
}; 

Ball ball; 
ball.location.x; 
ball.path.getPath(); 

或者,如果你必須使用->操作:

struct Location2 
{ 
    int * x; 
}; 

struct Ball2 
{ 
    Location2 * location; 
    Path *  path; 
}; 

Ball2 ball; 
ball->location->x; 
ball->path->getPath(); 
0
struct Location { 
    int x, y; 
}; 

struct Path { 
    vector<Location> getPath(); 
}; 

struct Ball { 
    Location location; 
    Path path; 
}; 

交替

struct Ball { 
    struct Location { 
     int x, y; 
    } location; 
    struct Path { 
     vector<Location> getPath(); 
    } path; 
};