可能重复:
如何为成员使用非默认构造函数?
我有当前的代码:
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
吗?这需要一个复制构造函数吗?