我一直收到这个错误。。。
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&’
这是我在这个方法的界面中的代码:
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
时,这个数字应该在哪里结束?没有道理,也不会起作用。你必须在这里传递一个正确类型的命名变量,这样函数就可以向其中写入一些内容
您的GetElement
修改其第二个参数。当Value
是i * 0.1
时,您希望它如何分配给Value
?
您可以将参数设为float const &
,但不能在函数中对其进行修改。
我认为你需要考虑一下你实际想做什么。
您似乎希望您的主循环看起来像这样:
for (int i = -5; i < 24; i++)
{
float f;
if (data1.GetElement(i, f) == true)
cout << "get " << i << " " << f << endl;
}
通过这种方式,您可以通过引用您的GetElement
方法来传递f
。您可以获得f
的地址(这就是&
符号的作用),但无法获得临时(i*0.1
)的地址。