4

サブクラスがその親の仮想関数の 1 つを実装しているかどうかを確認したいとします (これが悪いアーキテクチャのにおいがするかどうかは気にしないでください... これは演習です)。2 つの通常の関数が同一かどうかを確認したい場合は、 を確認するだけで済み&f == &gます。

// Plain old functions
void f() {}
void g() {}

...

std::cout << "&f " << &f << "\n";               // "1"  OK, for some reason func ptrs are converted
std::cout << "&g " << &f << "\n";               // "1"  to booleans when printed. I can dig it.
std::cout << "&f == &g " << (&f == &g) << "\n"; // "0"  Good, &f and &g are unequal as expected.

しかし、仮想メンバー関数では、動作が異なります。

// Base class with a virtual
struct A {
    virtual void f() {}
};

// Subclass which implements f
struct B : public A {
    void f() {}
};

// Subclass which doesn't implement f
struct C : public A {};

...

std::cout << "&A::f " << &A::f << "\n"; // "1"
std::cout << "&B::f " << &B::f << "\n"; // "1"
std::cout << "&C::f " << &C::f << "\n"; // "1" ... okay ... annoying, but alright.

std::cout << "&A::f == &B::f " << (&A::f == &B::f) << "\n"; // "1" DANGER - why does &A::f == &B::f if &f != &g?
std::cout << "&A::f == &C::f " << (&A::f == &C::f) << "\n"; // "1"
std::cout << "&B::f == &C::f " << (&B::f == &C::f) << "\n"; // "1"

std::cout << "(void*)&A::f " << (void*)&A::f << "\n";   // "0x4084b0" Here's what I was actually looking for.
std::cout << "(void*)&B::f " << (void*)&B::f << "\n";   // "0x4084bc" Good - the B::f differs from A::f as it should
std::cout << "(void*)&C::f " << (void*)&C::f << "\n";   // "0x4084b0" Perfect.

std::cout << "(void*)&A::f == (void*)&B::f " << ((void*)&A::f == (void*)&B::f) << "\n"; // "0"
std::cout << "(void*)&A::f == (void*)&C::f " << ((void*)&A::f == (void*)&C::f) << "\n"; // "1"
std::cout << "(void*)&B::f == (void*)&C::f " << ((void*)&B::f == (void*)&C::f) << "\n"; // "0" These are the comparison results I want

DANGERしたがって、私の質問は上記のコードでマークされています。なぜなら?&A::f == &B::f_ &f != &gにキャストせずに必要な比較を行う方法はありますかvoid*(これにより、ノイズの多いコンパイラ警告が発生します-Wpmf-conversions)。

4

0 に答える 0