在C ++中的struct中的struct

时间:2013-10-22 00:58:24

标签: c++ visual-studio-2010 struct

我需要帮助才能很好地理解struct

的用法

我有这段代码:

struct PCD
{
    PointCloud::Ptr cloud;
    std::string f_name;
    PCD() : cloud (new PointCloud) {};
};

但我不明白这行怎么可能:

PCD() : cloud (new PointCloud) {};

或更好,它做什么? struct中的struct

我在哪里可以找到一个很好的解释?

4 个答案:

答案 0 :(得分:5)

cloud是指向PointCloud对象的指针。它是PCD结构的成员。使用初始化列表初始化此结构时,该指针将分配一个新的PointCloud对象。

这可能在PointCloud struct / class:

中找到
typedef PointCloud* Ptr;

答案 1 :(得分:3)

PCD() : cloud (new PointCloud) {};

是一个PCD构造函数,它使用新的PointCloud实例初始化云变量。

struct PCD
{
    PointCloud::Ptr cloud;
    std::string f_name;
    PCD() : cloud (new PointCloud) {};
};

可以重写并可视化为:

struct PCD
{
public:
    PointCloud::Ptr cloud;
    std::string f_name;
    PCD();
};

PCD::PCD() : cloud (new PointCloud) {};

答案 2 :(得分:2)

结构是一种一切都公开的类。 在这里,您正在查看struct PCD的默认构造函数以及其数据成员之一的初始化。 我们不知道PointCloud是结构还是类,但似乎PCD在该类型的实例上包含指针。所以默认构造函数创建一个新实例。

答案 3 :(得分:2)

PCD() : cloud (new PointCloud) {};

这是结构PCD的默认构造函数。

:语法表示正在使用member initializer list来初始化一个或多个结构数据成员。在这种情况下,指针cloud被分配一个新的,动态分配的PointCloud对象。

成员初始化列表用于在执行构造函数体之前初始化非静态数据成员。它也是初始化参考类型成员的唯一方法。

有关构造函数和成员初始化列表的更多信息here