次の C++ 最終試験の準備として、この問題に取り組んでいます。
// What gets printed?
#include <iostream>
using namespace std;
class A {
public:
A(int a = 5) : i(a) { cout << "A" << endl; }
void foo() { cout << "this.i " << i << endl; }
virtual void print() const { cout << i << " in A" << endl; }
protected:
int i;
};
class B : public A {
public:
B() : A(1) { cout << "B default" << endl; }
void foo() { cout << i << " in B" << endl; }
void print() const { cout << i << " in B" << endl; }
};
int main() {
A *pa;
B b;
pa=&b;
pa->foo();
pa->print();
return 0;
}
そしてその出力は次のとおりです。
A
B default
this.i 1
1 in B
印刷されるのはスーパークラスからのコンストラクターのA
呼び出しによるものであり、ポインターを指すようにすると、の基本クラスメソッドにアクセスすることを理解していますが、代わりに値を印刷するにはどうすればよいですか?B
A
*pa
&b
foo
B::print()
A::print()