没有用于调用Foo :: Foo的匹配函数

时间:2011-10-21 07:52:19

标签: c++ class

我相信之前已经提出过这个问题。我试着寻找它但仍然无法弄清楚问题。我非常感谢能在这里得到任何帮助。感谢

我收到以下错误。一旦我调用Edge的构造函数,我就知道我没有初始化Vertex。但我似乎无法弄清楚如何。

10369.cpp: In constructor ‘Edge::Edge(Vertex, Vertex)’:
10369.cpp:34: error: no matching function for call to ‘Vertex::Vertex()’
10369.cpp:30: note: candidates are: Vertex::Vertex(int, int)
10369.cpp:6: note:                 Vertex::Vertex(const Vertex&)
10369.cpp:34: error: no matching function for call to ‘Vertex::Vertex()’
10369.cpp:30: note: candidates are: Vertex::Vertex(int, int)
10369.cpp:6: note:                 Vertex::Vertex(const Vertex&)

    #include <iostream>
    #include <math.h>
    using namespace std;

//Vertex in a graph, with x & y coordinates 
    class Vertex{
        int x , y;
        public:
            Vertex(int, int);
            ~Vertex();

            int GetX() {return x;};
            int GetY() {return y;};

    }; 

// Edge of a graph calculated from two vertices
    class Edge{
        Vertex U , V;
        float edge_weight;
            public:
                Edge(Vertex , Vertex);
                ~Edge();

                 float GetEdgeWeight() { return edge_weight; }


    };

    Vertex::Vertex(int _x , int _y){
        x = _x;
        y = _y;
    } 

// The edge weight is calculated using the pythagoras
    Edge::Edge(Vertex _U , Vertex _V){
        U = _U;
        V = _V; 
        int x = V.GetY() - U.GetY();
        int y = V.GetX() - U.GetX();
        edge_weight = sqrt(pow(x,2) + pow(y,2));

    }   
    int main (int argc , char *argv[]){

        Vertex V1(0,1) ; 
        Vertex V2(0,3);
        Edge E(V1, V2);
        float x = E.GetEdgeWeight();
        cout << x << endl;


        return 0;
    }

3 个答案:

答案 0 :(得分:6)

始终使用构造函数初始化列表初始化数据成员 - 您的Vertex没有默认构造函数,这是绝对必须使用初始化列表的情况之一。

Edge::Edge(Vertex U, Vertex V) : U(U), V(V), edge_weight(...) { }
Vertex::Vertex(int x, int y) : x(x), y(y) { }

答案 1 :(得分:4)

您的Vertex类没有默认构造函数。您默认初始化顶点,然后为它们分配一个值:

Edge::Edge(Vertex _U , Vertex _V){ // BTW _U is an identifier reserved for the implementation
        U = _U;
        V = _V; 

通常的方法不需要默认初始化:

Edge::Edge(Vertex U , Vertex V) : U(U), V(V) {

答案 2 :(得分:2)

更改Edge构造函数,如下所示:

Edge::Edge(Vertex _U , Vertex _V) :
    U(_U),
    V(_V)
{
    int x = V.GetY() - U.GetY();
    int y = V.GetX() - U.GetX();
    edge_weight = sqrt(pow(x,2) + pow(y,2));
}
相关问题