C++ 错误 C2100 - 非法间接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16147219/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 20:06:48  来源:igfitidea点击:

Error C2100 - Illegal Indirection

c++arraystemplatescompiler-errors

提问by Byron

I have a very simple program written to define a * operator in an array template class. When I try to compile it gives me an error "illegal indirection". Any help on the matter would be greatly appreciated!

我编写了一个非常简单的程序来在数组模板类中定义 * 运算符。当我尝试编译它给我一个错误“非法间接”。对此事的任何帮助将不胜感激!

This is the operator definition:

这是运算符定义:

template <typename T>                                                                   
NumericArray<T> NumericArray<T>::operator * (const int factor) const
{
NumericArray<T>* TempArray2 = new NumericArray<T>(Size());
for (int i=0; i<Size(); i++)
{
    *TempArray2[i] = ((GetElement(i))*(factor));
}
return *TempArray2;
}

And this is the implementation in the test main function:

这是测试主函数中的实现:

cout<<((*intArray1)*5).GetElement(0);                                   
cout<<((*intArray1)*5).GetElement(1);
cout<<((*intArray1)*5).GetElement(2);

Any ideas?

有任何想法吗?

采纳答案by Joseph Mansfield

Don't forget your operator precedencerules. It seems that you want:

不要忘记您的运算符优先级规则。看来你想要:

(*TempArray2)[i]

Otherwise your expression *TempArray2[i]is considered as *(TempArray2[i])and I suppose your NumericArray<T>type doesn't have the unary*operator overloaded.

否则你的表达式*TempArray2[i]被认为是*(TempArray2[i]),我想你的NumericArray<T>类型没有重载一元运算*符。

回答by molbdnilo

In *TempArray2[i], the *is applied to TempArray[2]because of the precedence rules, and there's a fair chance that the array elements don't have a unary *operator.

在 中*TempArray2[i],由于优先规则,*应用于TempArray[2],并且数组元素很可能没有一元运算*符。

Butyour use of dynamic allocation and then dereferencing to return by value means that you have a memory leak.
(You don't need newto create objects in C++ - you probably don't need to use it in maineither.)

但是您使用动态分配然后取消引用以按值返回意味着您有内存泄漏。
(您不需要new在 C++ 中创建对象 - 您可能也不需要在main其中使用它。)

This would be better (and avoids the whole indirection issue):

这会更好(并避免整个间接问题):

template <typename T>                                                                   
NumericArray<T> NumericArray<T>::operator * (int factor) const
{
    NumericArray<T> TempArray(Size());
    for (int i = 0; i < Size(); i++)
    {
        TempArray[i] = GetElement(i) * factor;
    }
    return TempArray;
}