मैं यह देख रहा था उत्तर और उपयोग करना चाहता था। हालाँकि, मुझे एक विभाजन दोष मिलता है, का उपयोग करते समय static_cast
तथा const_cast
, लेकिन अगर मैं एक अस्थायी चर का उपयोग सब कुछ ठीक है। यह स्पष्ट रूप से है क्योंकि गैर-कास्ट संस्करण bar()
इसे सेल्फ-ओवर कहते हैं। लेकिन मैं हालांकि static_cast
परिणामस्वरूप एक होगा const foo*
और फिर कास्ट संस्करण चुनें bar()
। ऐसा क्यों हैं?
#include <iostream>
using namespace std;
class foo
{
public:
void bar() const
{
cout << "const" << endl;
}
void bar()
{
cout << "non-const" << endl;
// static_cast<const decltype(this)>(this)->bar();
// const_cast<const decltype(this)>(this)->bar();
const auto& tmp = *this;
tmp.bar();
}
};
int main() {
foo A;
A.bar();
const foo B;
B.bar();
static_cast<const foo*>(&A)->bar();
return 0;
}
उत्तर:
जवाब के लिए 5 № 1decltype(this)
है foo*
। तथा const decltype(this)
है foo* const
.
आप केवल पॉइंटर्स cv-योग्यता को नहीं बदलते हैं, इसलिए हर बार गैर-कॉन्स्टल अधिभार चुना जाता है।