简体   繁体   English

下标运算符重载和对指针错误的引用

[英]Subscript operator overload and reference to pointer error

I'm struggling with a strange error for a while now and I need your help :D 我一段时间以来一直在遇到一个奇怪的错误,需要您的帮助:D

I have an 'Image' class declared like 我有一个像声明的“图像”类

template <typename P>
class Image {
// ...
public: // Operators 
    Color<P>*& operator [] ( unsigned int const& i );
// ...
}

Since it's the first time I overload this operator, I'm not really sure of it (especially the *& part...) 由于这是我第一次重载此运算符,因此我不太确定(尤其是*&部分...)

The troube appears when I tried something like : 当我尝试以下操作时,出现Troube:

/// Sample Code
Image<P> img; img[0][0] = Color<double>(1.0, 1.0, 1.0);

I get 我懂了

./src/Graphics/PNGWriter.cc:12:3: error: no match for ‘operator[]’ in ‘img[0]’
./src/Graphics/Image.cc:24:12: note: candidate is: Color<P>*& Image<P>::operator[](const unsigned int&) [with P = double] <near match>

Obviously the obscucate a bit more the solution to me... 显然,对我来说解决方案有点晦涩难懂...

Any idea ? 任何想法 ?

Thanks ! 谢谢 !

All "no match for '...'" errors mean the arguments in the call aren't compatible to the declared arguments for any functions or operators, so you should look to the argument declarations. 所有“不匹配'...'”错误都意味着调用中的参数与任何函数或运算符的声明参数都不兼容,因此您应查看参数声明。 Make argument to operator[] an unsigned int. operator[]的参数设为无符号整数。 Similarly, passing the returned pointer by reference is quite odd; 同样,通过引用传递返回的指针也很奇怪。 not necessarily bad, but highly suspect. 不一定不好,但高度怀疑。 In general, non-compound types should be passed by value. 通常,非复合类型应按值传递。

First of all, there is no need to pass so many things by reference. 首先,不需要通过引用传递很多东西。 Taking the unsigned int by value would almost certainly not slow things down; 几乎可以肯定的是,将unsigned int值作为值将不会减慢速度。 same about the reference to pointer. 关于指针的引用也一样。

This could be the problem, but I doubt it; 这可能是问题,但我对此表示怀疑。 I don't see why 0 wouldn't convert to a unsigned int const& . 我不明白为什么0不会转换为unsigned int const& Another possibility is that the image is actually const , but you failed to mention that in your paste. 另一种可能性是该图像实际上是const ,但是您在粘贴中没有提及。 Subscript operators generally come in pairs; 下标运算符通常成对出现。 you need to declare another one as Color<P> const* operator [] ( unsigned int i ) const; 您需要将另一个声明为Color<P> const* operator [] ( unsigned int i ) const; .

Note that img[0] is what is being complained about, so the = Color<double>(1.0, 1.0, 1.0); 注意img[0]是被抱怨的,所以= Color<double>(1.0, 1.0, 1.0); is probably not an issue (unless there's some SFINAE error I'm missing). 可能不是问题(除非我遗漏了一些SFINAE错误)。 Finally, make sure you haven't specialised Image for double . 最后,请确保您没有将Image专业化为double

EDIT: By the way, returning Color<P>*& has a severe disadvantage; 编辑:顺便说一句,返回Color<P>*&有一个严重的缺点。 someone could do img[0] = 0 , which was probably not the way the class was meant to be used. 有人可以做到img[0] = 0 ,这可能不是使用该类的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM