2016-03-21 279 views
-3

嗨我想调试一个程序,我收到的错误之一是'缺少构造函数的初始化'。我是否需要预先声明矢量,如何初始化它?缺少构造函数初始化

#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

你的问题在这里是你的类不是默认构造。

Vector rval; 

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

要创建Vector可以使用

Vector() = default; 

如果你有C++ 11或更高的默认构造函数,也可以使用

Vector() {} 

对于预C++ 11。

我不知道你正在尝试与

Vector v1(1,2) 

Vector做需要两个Point S和每个Point需要2倍的值。

+0

谢谢,关于Vector v1(1,2)这个程序,我必须为一个任务进行调试。所以它的一部分是问我是否需要这个,它做了什么或者它打算做什么。谢谢@NathanOliver – Bigboy6

+0

@ Bigboy6我不确定。 'Vector'需要'Point's,'1'不是'Point'。不知道编写代码的人究竟会做什么,我只能猜测。 – NathanOliver