如何将指向结构的指针传递给构造函数?

时间:2019-06-10 18:10:59

标签: c++ oop

我想将指针传递给构造函数(该结构的变量是一个数组,其中元素的值分别为x和y)。接下来,我想将此结构的每个变量的值x和y分配给类中该结构的相似变量值。

class Convex_quadrliteral
{
    protected:
    struct VC {
        float x, y;
    } vertice_coordinate[4];

    public:
    Convex_quadrliteral (VC *pointerVC);
};

Convex_quadrliteral::Convex_quadrliteral (VC *pointerVC) {  
    cout << "\nObject is being created" << endl;

    for (int i = 0; i < 4; i++) //variable initialisation
    {   
        vertice_coordinate[i].x = pointerVC[i].x;
        vertice_coordinate[i].y = pointerVC[i].y;
    }

    //object's properties output
    cout << "Properties: " << endl  
         << "A (" << vertice_coordinate[0].x << ", " << vertice_coordinate[0].y << ")" << endl
         << "B (" << vertice_coordinate[1].x << ", " << vertice_coordinate[1].y << ")" << endl
         << "C (" << vertice_coordinate[2].x << ", " << vertice_coordinate[2].y << ")" << endl
         << "D (" << vertice_coordinate[3].x << ", " << vertice_coordinate[3].y << ")" << endl;
}

int main()
{
    struct vertice_coordinate 
    {
        float x, y;
    };

    vertice_coordinate *pointerVC = new vertice_coordinate[4];

    for (int i = 0; i < 4; i++) {
        pointerVC[i].x = 2;
        pointerVC[i].y = 2;
    }

    Convex_quadrliteral figure_1(pointerVC);

我期望输出: A(2,2) B(2,2) C(2,2) D(2,2)

输出错误:没有声明与'Convex_quadrliteral :: Convex_quadrliteral(Convex_quadrliteral :: VC *)'C onvex_quadrliteral :: Convex_quadrliteral(VC * pointerVC)

1 个答案:

答案 0 :(得分:2)

您重新定义了VC结构,即使该结构看起来相同,编译器也会将它们视为两种不同的类型。定义一个结构,并在您的班级和main中使用它。