【问题标题】:C++: How to declare private member objects [duplicate]C ++:如何声明私有成员对象[重复]
【发布时间】:2012-10-22 15:21:50
【问题描述】:

可能重复:
How do you use the non-default constructor for a member?

我有当前代码:

class ImagePoint {
private:
    int row;
    int col;

public:
    ImagePoint(int row, int col){
        this->row = row;
        this->col = col;
    }

    int get_row(){
        return this->row;
    }

    int get_col(){
        return this->col;
    }
};

我想这样做:

class TrainingDataPoint{
private:
    ImagePoint point;
public:
    TrainingDataPoint(ImagePoint image_point){
        this->point = image_point;
    }
};

但这不会编译,因为ImagePoint point; 行要求ImagePoint 类有一个空的构造函数。替代方案(根据我的阅读)说我应该使用指针:

class TrainingDataPoint{
private:
    ImagePoint * point;
public:
    TrainingDataPoint(ImagePoint image_point){
        this->point = &image_point;
    }
};

然而,一旦构造函数完成运行,这个指针会指向一个被清除的对象吗?如果是这样,我是否必须复制image_point?这需要复制构造函数吗?

【问题讨论】:

    标签: c++ initialization copy-constructor member


    【解决方案1】:

    您需要使用构造函数初始化列表:

    TrainingDataPoint(const ImagePoint& image_point) : point(image_point){
    }
    

    如果可能,您应该更喜欢这个。但是,在某些情况下您必须使用它:

    • 没有默认构造函数的成员(如您所述)
    • 成员参考
    • const会员

    【讨论】:

    • 这将复制 image_point 并将其存储在 point 中?
    • 谢谢,我会在 10 分钟内接受答复,如果 SO 允许的话:)。
    【解决方案2】:

    您不需要知道这些事情,因为您不会使用该代码,而只是为了完整性:

    一旦构造函数完成运行,这个指针会指向一个 清除对象?

    是的,参数image_point在构造函数退出时被销毁。所以你是对的,将指向它的指针存储在对象中并在之后尝试使用它是不正确的。

    如果是这样,我是否必须制作 image_point 的副本?

    可以这样做,但您不打算使用此代码的原因是您将其复制到 哪里 的问题。

    这需要复制构造函数吗?

    是的,但是ImagePoint 已经有一个复制构造函数,编译器会自动为您生成。

    【讨论】:

      【解决方案3】:

      只需使用构造函数初始化列表:

      class TrainingDataPoint 
      {
      private:
          ImagePoint point;
      public:
          TrainingDataPoint(const ImagePoint &imgpt) 
               : point(imgpt)
          {
              // other code here as necessary. point has already been initialized
          }
      };
      

      【讨论】:

        【解决方案4】:

        你读错了。正确的选择是使用初始化列表

        class TrainingDataPoint{
        private:
            ImagePoint point;
        public:
            TrainingDataPoint(ImagePoint image_point) : point(image_point){
            }
        };
        

        顺便说一句,这与 private 成员无关,如果他们是公开的,你会遇到同样的问题。

        【讨论】:

          【解决方案5】:

          使用构造函数初始化器将解决您的问题。

          TrainingDataPoint(const ImagePoint& image_point) : point(image_point){
          }
          

          【讨论】:

            猜你喜欢
            • 2017-08-04
            • 2011-11-16
            • 2011-04-04
            • 2014-08-25
            • 1970-01-01
            • 1970-01-01
            • 2011-02-24
            • 2023-04-11
            • 1970-01-01
            相关资源
            最近更新 更多