当类具有多个默认构造函数C++时声明对象数组

Declare array of objects when the class has more then one default constructor C++

本文关键字:C++ 声明 对象 数组 构造函数 默认      更新时间:2023-10-16

你好,我有class point,工作是制作array of points(同一类的对象),但该类有多个构造函数。如何声明我想要在数组中加入哪一个?代码:

class point
{
private:
    double pointX, pointY;
    string color;
    int form;
public:
    point();
    point(double, double, string color = "red", int form = 2);
    point(string color = "red", int form = 2);
    ~point() {
        cout << "Deleting object point" << endl;
    }
    inline void print();
    inline void distance();
};
point::point(double x, double y, string color = "red", int form = 2) {
    cout << "enter x coordinate of the point x = "; cin >> pointX;
    cout << "enter y coordinate of the point y = "; cin >> pointY;
}
point::point(string color = "red", int form = 2) {
    cout << "enter x coordinate of the point x = "; cin >> pointX;
    cout << "enter y coordinate of the point y = "; cin >> pointY;
}
point::point() {
    cout << "enter x coordinate of the point x = "; cin >> pointX;
    cout << "enter y coordinate of the point y = "; cin >> pointY;
    cout << "enter color of the point "; getline(cin, color);
    cout << "enter number form 1 - 3 for the form of the point "; cin >> form;
}
inline void point::print() {
    cout << "the x coordinate of the point is x = " << pointX << endl;
    cout << "the y coordiante of the point is y = " << pointY << endl;
    cout << "the color of the point is " << color << endl;
    if (form = 1) cout << "the form is circle" << endl;
    if (form = 2) cout << "the form is square" << endl;
    if (form = 2) cout << "the form is cross" << endl;
}
inline void point::distance() {
    double z;
    z = sqrt(pointX*pointX + pointY*pointY);
    cout << "distance between the point and the start of coordinate system is " << z << endl;
}
double pointDistatnce() {
    double z, x, y;
    point points = new point[4];
}


!!! point points = new point[4];` // here must be the array of objects but it shows me error that "class point has more than one default constructor"?

我想使用没有参数的构造函数,以便用户构建自己的点。以下是错误列表中的错误;

!! no suitable constructor exists to convert from "point    
!! class "point" has more than one default constructor  

point();声明一个默认构造函数。 point(string color = "red", int form = 2); 要么去掉第一个,只使用第二个,要么去掉第二个color的默认值。

根据您发布的额外信息进行编辑:您正在寻找编译器来阅读程序员的想法。 您定义了一个没有参数的构造函数来执行一项操作,但您定义了一个具有两个执行不同操作的可选参数的构造函数。 当调用构造函数并且没有给出任何参数时,这是否意味着它应该在没有参数的情况下执行,或者是否意味着它应该使用两个可选参数的默认值执行。

这些都没有改变我原来的答案。 这只是意味着您需要思考一下才能使用该答案。 在您最初提供的部分代码中,人们可能希望每个构造函数都可以在没有参数的情况下调用,彼此是冗余的,因此只需删除冗余即可修复它。 但是,由于您希望程序员能够调用两个不同的构造函数之一,因此您需要想一种方法来告诉编译器应该使用哪一个。

在重新考虑设计时,您还应该尝试放弃在构造函数中使用cin的想法。 这在技术上并没有。 但这是一个足够糟糕的主意,你不应该这样做。