C++:如何声明私有成员对象

Aly*_*Aly 0 c++ initialization member copy-constructor

可能重复:
如何为成员使用非默认构造函数?

我有当前的代码:

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;
    }
};
Run Code Online (Sandbox Code Playgroud)

我想这样做:

class TrainingDataPoint{
private:
    ImagePoint point;
public:
    TrainingDataPoint(ImagePoint image_point){
        this->point = image_point;
    }
};
Run Code Online (Sandbox Code Playgroud)

但是这不会编译,因为该行ImagePoint point;要求ImagePoint类具有空构造函数.替代方案(从我读过的)说我应该使用指针:

class TrainingDataPoint{
private:
    ImagePoint * point;
public:
    TrainingDataPoint(ImagePoint image_point){
        this->point = &image_point;
    }
};
Run Code Online (Sandbox Code Playgroud)

但是,一旦构造函数完成运行,此指针是否指向已清除的对象?如果是的话,我是否必须复制一份image_point?这需要复制构造函数吗?

Luc*_*ore 9

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

TrainingDataPoint(const ImagePoint& image_point) : point(image_point){
}
Run Code Online (Sandbox Code Playgroud)

你应该尽可能地喜欢这个.但是,有些情况下您必须使用它:

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