c++ - C++ 类中的 float 和 double 错误

标签 c++ class

我一直收到这个错误...

lab11a.cpp: In function ‘int main()’:
lab11a.cpp:120:34: error: no matching function for call to ‘SafeArray::GetElement(int&, double)’
lab11a.cpp:120:34: note: candidate is:
lab11a.cpp:48:6: note: bool SafeArray::GetElement(int, float&) const
lab11a.cpp:48:6: note:   no known conversion for argument 2 from ‘double’ to ‘float&’
lab11a.cpp:121:38: error: no matching function for call to ‘SafeArray::GetElement(int&, double)’
lab11a.cpp:121:38: note: candidate is:
lab11a.cpp:48:6: note: bool SafeArray::GetElement(int, float&) const
lab11a.cpp:48:6: note:   no known conversion for argument 2 from ‘double’ to ‘float&’

这是我在我的接口(interface)中为这个方法准备的代码:

bool GetElement(const int i, float & Value) const;

这是我实现中的代码:

bool SafeArray::GetElement(const int i, float & Value) const 
{
    bool Success = false;
    if ((i >= 0) && (i < SIZE))
    {
        Success = true;
        Value = Array[i];
    }
    return Success;
}

这是我的主程序中的代码:

for (int i = -5; i < 24; i++)
{
    data1.GetElement(i, i * 0.1);
    if (data1.GetElement(i, i * 0.1) == true)
        cout << "get " << i << " " << i * 0.1 << endl;
}

最佳答案

您的函数 GetElement 引用了一个 float 并在那里写入一个值。但是,您使用 i * 0.1 调用它,这是一个未命名的临时变量,不能为参数 float & Value 传递。想一想:在 GetElement 中,您将一些内容写入 Value,当您将 i * 0.1 作为 Value 传递时,这个数字应该在哪里结束?没有意义,也不会起作用。您必须在此处传递正确类型的命名变量,以便函数可以向其中写入内容。

关于c++ - C++ 类中的 float 和 double 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23093376/

相关文章:

Java:在没有 KeyListener 或使用任何其他自定义类的情况下捕获按键事件

c++ - 在C++ AMP阵列中,数据被复制了多少次?

c++ - 如何在 C++ 中将整个文本文件复制到 char 数组中

c++ - cplusplus 导入 csv 不识别第一列?

ios - 如何快速检查对象属于类或结构

java - java中不同类中通过静态方法设置和获取静态变量值

javascript - 是否可以重新定义 JavaScript 类的方法?

c++ - 类的私有(private)成员 - 在此上下文中

c++ - 不需要时静态初始化

java - 创建一个对象并将其打印出来,但结果打印了引用。怎么解决这个问题呢?