2012-10-22 32 views
0

可能重复:
How do you use the non-default constructor for a member?C++:如何声明私有成员对象

我当前的代码:

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?这将需要一个复制构造函数吗?

回答

9

你需要使用一个构造函数初始化列表:

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

你应该更喜欢这种可能的情况下。不过,也有情况下,您必须使用它:

  • 成员没有默认构造函数(如你所提到的)
  • 成员引用
  • const成员
+0

这将使image_point的副本,并将其存储点? – Aly

+0

@是的。 [填写] –

+0

谢谢,当SO让我时,我会在10分钟内接受答案:)。 – Aly

1

您已经阅读什么是错的。正确的选择是使用一个初始化列表

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

通过此无关与私人成员的方式,你会得到同样的问题,如果他们是公众。

1

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

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

你不需要知道这些事情,因为你不打算使用该代码,但只是为了完整性:

一次构造函数已经运行完毕,这个指针会指向一个清除对象的 ?

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

如果是这样,我是否必须复制image_point?

这将做到这一点,但你不打算使用这个代码的原因就是你会复制它的的问题。

这是否需要复制构造函数?

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

1

使用构造函数初始值设定项可以解决您的问题。

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