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

标签 c++ initialization copy-constructor member

<分区>

Possible Duplicate:
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?这需要复制构造函数吗?

最佳答案

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

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

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

  • 没有默认构造函数的成员(如您所述)
  • 成员推荐
  • const 成员

关于C++:如何声明私有(private)成员对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13014545/

相关文章:

c++ - 我如何拆除多线程 C++ 中的观察者关系?

c++ - 为 float 据类型赋值会导致程序崩溃

c++ - Qt 应用程序在使用 DLL 时崩溃,如果导出函数未声明 APIENTRY 则工作正常

c++ - 在 for 循环中声明 vector

c++ - 如何使用构造函数初始值设定项列表中的 n 个元素初始化 std::vector<std::time_t>

amazon-web-services - 更好的初始化

c++ - 创建带有和不带有 new 关键字的 C++ 对象

c++ - 使用默认值输入模拟参数

c++ - 在没有复制构造函数的情况下实例化 std::vector 的唯一元素

c++ - 从现有对象创建对象