缺少初始化的构造函数

时间:2016-03-21 17:08:41

标签: c++ vector constructor

您好我正在尝试调试程序,我收到的错误之一是“缺少初始化构造函数”。我是否需要预先声明向量以及如何初始化它?

#include <iostream>
#include <vector>

using namespace std;

class Point {
private:
    double x;
    double y;
public:
    double get_x() { return x; }
    double get_y() { return y; }
    bool set_x(double arg) {
        x = arg;
        return true;
    }
    bool set_y(double arg) {
        y = arg;
        return true;
    }
    Point() : x(0), y(0) {}
    Point(double argx, double argy) : x(argx), y(argy) {
    }
};


class Vector {
private:
    Point A;
    Point B;
public:
    Point get_A() { return A; }
    Point get_B() { return B; }
    Vector(const Point &arg1, const Point &arg2) : A(arg1), B(arg2)
    {
        //this->A = arg1;
        //this->B = arg2;
        //A = arg1;
        //B = arg2;
    }
    void set_A(const Point &arg) {
        A = arg;
    }
    void set_B(const Point &arg) {
        B = arg;
    }
    static Vector add_vector(const Vector &vector1, const Vector &vector2) {
        if (&vector1.B != &vector2.A) {

            //Error 1 Vector V1 No Matching constructor for initialization for 'vector'

            Vector rval;
            return rval;
        }

        Point one = vector1.A;
        Point two = vector2.B;

        Vector newvector(one, two);
        //newvector.A = one;
        //newvector.B = two;
        return newvector;

    }
    Vector add_vector(const Vector &arg) {
        // Type of this?  Vector *; These three lines are equivalent:
        //Point one = this->A;
        //Point one = (*this).A;
        Point one = A;

        Point two = arg.B;

        Vector newvector(one, two);
        //newvector.A = one;
        //newvector.B = two;
        return newvector;
    }

};


int main() {

    //Error 2 Vector v No Matching constructor for initialization for 'vector'


   Vector v;
    cout << "(" << v.get_A().get_x() << ", " << v.get_A().get_y() << "),\n" <<
    "(" << v.get_B().get_x() << ", " << v.get_B().get_y() << ")\n";

    //Error 3    Vector V1 No Matching constructor for initialization for 'vector'


    Vector v1(1,2), v2(2,3);
    Vector res = Vector::add_vector(v1, v2);
    cout << "(" << res.get_A().get_x() << ", " << res.get_A().get_y() << "),\n" << 
    "(" << res.get_B().get_x() << ", " << res.get_B().get_y() << ")\n";

}

1 个答案:

答案 0 :(得分:1)

您的问题是您的类不是默认构造的。

Vector rval;

需要默认构造函数。由于您提供了用户定义的构造函数,因此编译器将不再为您创建默认构造函数。

要为Vector创建默认构造函数,您可以使用

Vector() = default;

如果你有C ++ 11或更高版本,或者你可以使用

Vector() {}

对于预C ++ 11。

我不确定你要用

做什么
Vector v1(1,2)

Vector需要两个Point,每个Point需要2个值。