c++ - 在 C++ 中作为参数传递时,数组隐式转换为容器类

标签 c++ arrays constructor instantiation implicit

我正在做一个项目,在研究代码时,我遇到了以下奇怪的事情。

我有两个类(class)。第一个在表示笛卡尔坐标的数组中包含三个 float ,并定义了获取这些点的方法;

class foo
{
protected:
    float m_Coordinates[3];

public:
    foo(float coordinates[3]);
    void GetPoints(int resultArray[]);
};

foo::foo(int coordinates[3])
{
    std::copy(coordinates, coordinates+3, m_Coordinates);
}

void foo::GetPoints(float resultArray[])
{
    std::copy(m_Coordinates, m_Coordinates+3, resultArray);
}

第二个类也存储一个 float 数组,但它的构造函数使用 foo 作为包装类来传递值:

class bar
{
protected:
    float m_MoreCoordinates[3];

public:
    bar(foo f);
};

bar::bar(foo f)
{
    f.GetPoints(m_MoreCoordinates);
    //m_MoreCoordinates is passed by reference, so the values in
    //m_MoreCoordinates are equal to the values in f.m_Coordinates
    //after this line executes
}

请忽略我对这段代码采用的方法简直太可怕了。它最初是作为使用数组的实验。将它们作为参数传递,将它们作为返回类型等。

好的。这是我注意到一些奇怪的地方。如果我声明一个 float 数组并将它们作为参数传递给 bar 的构造函数,编译器将生成类 foo 的一个实例并将其传递给 bar。请参阅下面的示例代码:

int main(int argv, char** argc)
{
    float coordinates[] = {1.0f, 2.1f, 3.0f};


    //Here the compiler creates an instance of class foo and passes 
    //coordinates as the argument to the constructor. It then passes 
    //the resulting class to bar's constructor.
    bar* b = new bar(coordinates);

    //Effectively, the compiler turns the previous line into
    //bar* b = new bar(foo(coordinates));

    return 0;
}

当我看到这个时,我认为这是代码的一个非常简洁的功能,并且想知道它是如何发生的以及为什么会发生。这样做安全吗?我不明白它是如何工作的,所以我不想依赖它。如果有人能解释这是如何工作的,我将不胜感激。

编辑: 感谢 Mankarse 指出如何在 main 中执行转换。最初,我有:

//Effectively, the compiler turns the previous line into
//bar* b = new bar(*(new foo(coordinates)));

最佳答案

如您所料,编译器正在隐式创建一个 foo 对象并将其传递给 bar。通常,这被认为有点危险,因为 foo 是在不知情的情况下构建的,为避免这种情况,您可以将 foo 的构造函数声明为 explicit。在这种情况下,编译器不会从 float 组隐式创建 foo,您将收到编译器错误。

关于c++ - 在 C++ 中作为参数传递时,数组隐式转换为容器类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9338485/

相关文章:

c - 在查找最大对和时使用指针

c++ - 如何在 C++ 中使用 boost 正则表达式解析转义元素 '\' 和 unicode 字符 '\u'

c++ - Shuffle 函数无法使用指针来工作

c++ - 如何写短这个 "or"语句是不是?

java - 围绕 superfirst 工作

c++ - 是否可以初始化 const Eigen 矩阵?

Java:在子类化中使用通用通配符

c++ - 如何将队列元素插入 vector 中?

c++ - VTK图像数据,访问阵列中的1张图像

javascript - 如何从单个数组对象中的多个数组对象创建数组?