C ++类和嵌套成员

时间:2010-01-29 00:32:25

标签: c++ class

我不知道怎么称呼它。基本上我想创建一个嵌套成员的类。

示例:

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

现在我只知道如何建立公共和私人成员,如

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

由于

3 个答案:

答案 0 :(得分: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();

答案 1 :(得分: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();

答案 2 :(得分: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;
};