سؤال

النظر في الفصول التالية: giveacodicetagpre.

أود إنشاء وظيفة عضوا في NamedPoint - Coord () - أن إرجاع مرجع من نوع النقوع المقابل لنقطة السماوية.

على سبيل المثال، أود أن شيء مثل: giveacodicetagpre.

لكنني أحصل على تحذير من المتغيرات المؤقتة وأنا لست مجنونا حيال ذلك.

بالطبع، الأعمال التالية: giveacodicetagpre.

لكنني أفضل إرجاع مرجع.

هل يعرف أحد إذا كان ذلك ممكنا باستخدام فصول موروثة؟

آسف لعدم شرح نقطة الوظيفة. أنا زيادة التحميل== المشغل بشكل مختلف عن الاتساف ونقعة. من شأنها أن تحقق النقاط ببساطة {x و y} وسمو اسم المسمى {ID و X و Y}. إذا نسيت إلقاء نقطة اسم اسم الوظيفة حتى يتم إجراء ذلك قبل ذلك== الاختبار، فسأي استخدام الإصدار الخاطئ.

لذلك، بينما أدرك أن giveacodicetagpre.

سيعطيني ما أريد، سأفضل استخدام شيء مثل giveacodicetagpre.

الذي أعتقد أنه أكثر وضوحا حول ما يجري.

هل كانت مفيدة؟

المحلول

What's the point of the function? NamedPoint is implicitly convertible to Coord anyway:

void foo(Coord& c)
{
    c._x = 5;
}

NamedCoord nc(0, 1, 2);
foo(nc); // c references the Coord part of nc

Anyway, your function should simply use this conversion:

const Coord& NamedPoint::coord()
{
    // Bad: takes the value of *this and slices off
    // the derived bits, leaving a temporary Coord.
    /* return ((Coord)*this); */

    // Good: takes the value of *this and refers
    // to the base bits, no temporaries.
    return *this;

    // (Same as:)
    /* return ((Coord&)*this); */
}

نصائح أخرى

@GMan gives the main solution.

However, it might be interesting to note in more detail the problem:

const Coord& NamedPoint::coord()
{
    return ((Coord)*this);
}

This is much the same as:

const Coord& NamedPoint::coord()
{
    Coord c = *this;
    return c;
}

Here it is clear that you are returning a reference to a temporary on the stack, which makes the reference to it useless, and hence the warning.

Now in the case presented, Coord is the base class and hence we have the simple solution given by @Gman.

In the general case, the principle is that if you want a reference to something, you better make sure that something will still be around.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top