Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

c++ - no matching function for call to ' '

I was given to implement the function:

 "static double distanta (const Complex&, const Complex&);"

which return the distance between two Complex numbers. The definition of the function it is inside the Complex class and I have implemented it like that:

double Complex::distanta(const Complex &a, const Complex &b)
{    
    double x = a.real() - b.real();
    double y = a.imag() - b.imag();

    return sqrt(x * x + y * y);
}

As far as I know a static function can only access static members and my class only has

double _re;
double _im;

as data members.

Within the main function I have called it as:

#include <iostream>
#include "complex.h"

using namespace std;

int main()
{
    Complex* firstComplexNumber; 
    firstComplexNumber = new Complex(81, 93);

    cout << "Numarul complex este: " << *firstComplexNumber << endl;

    Complex* secondComplexNumber;
    secondComplexNumber = new Complex(31, 19);

    cout << "Distanta dintre cele doua numere" <<endl << endl;
    Complex::distanta(firstComplexNumber, secondComplexNumber);
    return 0;
}

and the error I get is:

error: no matching function for call to 'Complex::distanta(Complex*&, Complex*&)'

Could you please tell me what is it that I'm doing wrong? Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are passing pointers (Complex*) when your function takes references (const Complex&). A reference and a pointer are entirely different things. When a function expects a reference argument, you need to pass it the object directly. The reference only means that the object is not copied.

To get an object to pass to your function, you would need to dereference your pointers:

Complex::distanta(*firstComplexNumber, *secondComplexNumber);

Or get your function to take pointer arguments.

However, I wouldn't really suggest either of the above solutions. Since you don't need dynamic allocation here (and you are leaking memory because you don't delete what you have newed), you're better off not using pointers in the first place:

Complex firstComplexNumber(81, 93);
Complex secondComplexNumber(31, 19);
Complex::distanta(firstComplexNumber, secondComplexNumber);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...