在其他类方法中使用构造函数中的对象

时间:2015-10-08 17:03:57

标签: c++ object methods constructor

我有一个具有以下定义的课程:

PlotterAxis::position()

现在我想访问long PlotterAxis::position() { return pos; } 中的步进对象,如

{{1}}

但我不知道如何在PlotterAxis的其他方法中使用构造函数参数创建对象。

2 个答案:

答案 0 :(得分:0)

我看不到您提到的访问权限,但您需要将指针存储在PlotterAxis中,这是肯定的:

class PlotterAxis
{
public:
    PlotterAxis(Stepper *stepper);
    long position();

private:
    // raw pointer, beware of stepper's lifetime and copy semantics of PlotterAxis
    Stepper *stepper;
    long pos;
};

PlotterAxis::PlotterAxis(Stepper *stepper) : stepper(stepper) {}

然后你可以访问它:

long PlotterAxis::position()
{
    stepper->doSomething();
    return pos;
}

答案 1 :(得分:0)

  

但我不知道如何在PlotterAxis的其他方法中使用构造函数参数创建对象。

您必须将输入PlotterAxis存储在您的类中作为成员变量,并在需要的地方使用它。

class PlotterAxis
{
   public:
      PlotterAxis(Stepper *stepper) : stepper_(stepper) {}
      long position();

   private:

      Stepper *stepper_;
      long pos;
};

long PlotterAxis::position()
{
    // Use stepper_ if you need to.
    stepper_->someFunction();
    return pos;
}
相关问题