C++传递类数组

C++ passing an array of classes

本文关键字:数组 C++      更新时间:2023-10-16

>谁能帮我传递类数组的语法到另一个类。 将类数组传递给另一个类数组的语法上课打败了我。 类行尝试由点数组,但原型不匹配。

#include    <iostream>
using namespace std;
class point {
public:
    point() {}
    point(int x, int y) : X(x), Y(y) {}
    void setXY(int x, int y) { X = x; Y = y; }
    int getX() { return X; }
    int getY() { return Y; }
private:
    int X, Y;
};
class line {
public:
    line(point *points, int);  // Problem line.
private:
    point *coords;
    int numpoints;
};
int main() {
    point   points[3];
    points[0].setXY(3, 5);
    points[1].setXY(7, 9);
    points[2].setXY(1, 6);
    line    l(points, 3);    // Problem line.
    return 0;
}

错误信息:cygdrive/c/Tmp/cc4mAXRG.o:a.cpp:(.text+0xa7):对'line::line(point*, int)'的未定义引用

您需要为行类定义一个构造函数 - 您只提供了一个声明。

#include    <iostream>
using namespace std;
class point {
public:
    point() {}
    point(int x, int y) : X(x), Y(y) {}
    void setXY(int x, int y) { X = x; Y = y; }
    int getX() { return X; }
    int getY() { return Y; }
private:
    int X, Y;
};
class line {
public:
    line(point *points, int count)
     : coords(points), numpoints(count) {}
private:
    point *coords;
    int numpoints;
};
int main() {
    point   points[3];
    points[0].setXY(3, 5);
    points[1].setXY(7, 9);
    points[2].setXY(1, 6);
    line    l(points, 3);
    return 0;
}

我建议看看定义和声明之间的区别。此外,您应该考虑在line类中维护一个std::vector<point>来管理积分。然后,您的行类可能表现为:

#include <vector>
class line {
public:
    line(std::vector<point> points)
     : coords(points), numpoints(coords.size()) {}
private:
    std::vector<point> coords;
    int numpoints;
};

您没有为构造函数提供定义。

尝试:

line(point *points, int np) : coords(points), numpoints(np) {}

缺少构造函数"line"的主体。您仅定义原型。