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

时间:2016-01-19 17:26:36

标签: c++ class constructor

你好我有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  

1 个答案:

答案 0 :(得分:3)

point();声明一个默认构造函数。那么point(string color = "red", int form = 2);要么摆脱第一个,只使用第二个,或者在第二个中除去color的默认值。

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

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

在重新考虑您的设计时,您还应该尝试放弃在构造函数中使用cin的想法。从技术上讲,它不是错误。但是你不应该这样做是一个糟糕的想法。