opMul
Bill Baxter
dnewsgroup at billbaxter.com
Mon Mar 3 13:35:31 PST 2008
Denton Cockburn wrote:
> On Tue, 04 Mar 2008 05:56:57 +0900, Bill Baxter wrote:
>
>> Denton Cockburn wrote:
>
>>> so what I want is this:
>>>
>>> struct Foo
>>> {
>>> int bar;
>>> void doStuff(const Foo b)
>>> {
>>> bar += b.bar; /* I want an error here */
>>> }
>> You're not changing b, so you're not going to get an error there.
>
> You're right, that was a mistake.
>
> I misphrased my whole query (I misread the compiler error message).
> The concern is still there though, here's a sample of code that produces
> the message.
>
> struct Foo
> {
> int x;
>
> Foo opMul(const Foo b)
> {
> Foo f;
> f.x = x * b.x;
>
> return f;
> }
> }
>
> void main()
> {
> Foo f;
> Foo y;
> f.x = 6;
> y.x = 7;
>
> const(Foo) t = f;
> Foo p = t * y;
> }
>
> produces this error:
> test.d(24): function test.Foo.opMul (const(Foo)) does not match parameter types (Foo)
> test.d(24): Error: t.opMul can only be called on a mutable object, not const(Foo)
>
>
> So my question SHOULD have been:
>
> Why can't opMul et al be called on a constant object (reference)?
>
> Sorry for the previous confusion.
Ok *that's* because saying the parameter is const doesn't mean the
'this' pointer is const.
To make the hidden 'this' parameter const too you need to use
const Foo opMul(const Foo b) {...}
That const out front may look like it's modifying the return value, but
its not. That would be
const(Foo) opMul(const Foo b) {...}
--bb
More information about the Digitalmars-d
mailing list