c++ - 调用 ' ' 没有匹配的函数

标签 c++

我被赋予实现功能:

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

返回两个复数之间的距离。函数的定义在 Complex 类中,我已经这样实现了:

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);
}

据我所知,静态函数只能访问静态成员,而我的类只有

double _re;
double _im;

作为数据成员。

在主函数中,我将其称为:

#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;
}

我得到的错误是:

错误:没有匹配函数调用 'Complex::distanta(Complex*&, Complex*&)'

你能告诉我我做错了什么吗? 谢谢!

最佳答案

当您的函数采用引用 (const Complex&) 时,您正在传递指针 (Complex*)。引用和指针是完全不同的东西。当函数需要引用参数时,您需要直接将对象传递给它。引用只表示不复制对象。

要让一个对象传递给你的函数,你需要取消引用你的指针:

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

或者让你的函数接受指针参数。

但是,我不会真正建议上述任何一种解决方案。由于您在这里不需要动态分配(并且您正在泄漏内存,因为您没有 delete 您拥有 newed 的内容),因此最好不要使用指针首先:

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

关于c++ - 调用 ' ' 没有匹配的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15113856/

相关文章:

c++ - c++中函数指针语法的理解

c++ - OpenGL GLSL 着色器版本

c++ - 如何在 C++ 中调用 void foo(int (&)[]) {}?

c++ - LNK2005 - ATL 基类符号已定义 - 根本原因是什么?

C++将参数包扩展为数组元组

c++ - 静态成员初始值设定项的 lambda 作用域

c++ - C++ 中变量存储在内存中的什么位置?

c++ - 如何实现unsigned abs(int)?

c++ - 开关盒标签上的 PC-lint : Violates MISRA C++ 2008 Required Rule 5-0-12

c++ - 在 C++ 中创建一个大数组