VTableについてたくさん読んだ後でも、未回答の質問が1つあります。
次のクラスを考えると:
#include <iostream>
using namespace std;
class Shape {
public:
int* a;
Shape(){
cout<<"default Shape ctor"<<endl;
a = new int(15); // default
}
Shape(int n){
a = new int(n);
cout<<"Shape(n) constructor"<<endl;
}
// copy constructor
Shape(const Shape& s){
cout<<"copy constructor"<<endl;
a = new int(*(s.a));
}
Shape& operator=(const Shape& s){
cout<<"operator="<<endl;
if (&s == (this))
return (*this);
// this.clear();
a = new int(*(s.a));
return (*this);
}
virtual void draw(){
cout<<"print Shape the number is "<<*a<<endl;
};
virtual ~Shape(){
delete a;
cout<<"Shape distructor"<<endl;
}
};
class Circle : public Shape {
public:
int b;
Circle() {
cout<<"Circle constructor"<<endl;
b=5;
}
virtual void draw() {
cout<<"print Circle. The number is "<<b<<endl;
}
~Circle(){
cout<<"Circle distructor"<<endl;
}
};
および次のテスト:
static void test2(){
Circle* c = new Circle();
cout<<"size of *c is "<<sizeof(*c)<<endl;
Shape* s = c;
cout<<"size of *s is "<<sizeof(*s)<<endl;
s->draw();
}
私はこの出力を取得します:
default Shape ctor
Circle constructor
size of *c is 12
size of *s is 8
print Circle. The number is 5
私の質問は次のとおりです。sがCircle::drawをどのようにアドレス指定するかは知っていますが、変数b = 5をどのように知ることができますか?このテストが示すように、sにはこの情報がありません。ここで何が欠けていますか?
ありがとう!
OKみんな。迅速な回答をありがとう...
あなたの回答から、Circle :: draw()(* this)はCircleタイプであることがわかりました。わかった。私の質問はこれに変わりました。私はsをShape*タイプにしたいだけだったので、つまり、プログラムではShape品質だけが必要でした。次の4バイト(Circleのb変数)がコンパイラによって何らかの形で取得される可能性はありますか?その場合、明らかにCircle :: draw()は期待どおりに機能しません。
そうでない場合、コンパイラは、sの「終了」の後にこれらの次の4バイトが必要であることをどのように認識しますか?