从 base-class 指针调用 sub-class 方法?
Calling sub-class method from a base-class pointer?
不知道起什么标题,希望有经验的whosebug.com网友改进。
假设我们有 class A
class A {
void hello(){ cout << "i'm an A" << endl; }
}
及其sub-class B
class B: public A {
void hello(){ cout << "i'm a B" << endl; }
}
然后我们在程序的某处做了
A* array[2];
array[0] = new A;
array[1] = new B;
array[0]->hello(); // output: "i'm an A"
array[1]->hello(); // output: "i'm a B"
为什么 array[1].hello();
不输出 I'm a B
,因为我们为 base-class 指针实例化了 B
object?以及如何实现它?
您必须使 hello
成为虚函数:
class A {
virtual void hello() { cout << "i'm an A" << endl; }
};
class B : public A {
virtual void hello() override { cout << "i'm a B" << endl; } // 1)
};
这告诉编译器实际函数不应该由静态类型(指针或引用的类型)决定,而是由对象的动态(运行-时间)类型决定。
1) override
关键字告诉编译器检查该函数是否实际上覆盖了基 class 中的 hello
函数(有助于例如捕获拼写错误或参数类型)。
这里有几个变化:
make function hello in class A, a virtual
and public:
因为默认是 private
class A {
public:
virtual void hello(){ cout << "i'm an A" << endl; }
};
同样在classB
virtual
打个招呼
class B: public A {
virtual void hello(){ cout << "i'm a B" << endl; }
};
由于您在class B 中继承了class A,派生class B 将调用Base class 中的函数。您需要覆盖 class B 中的函数,因为您想要更改基础 class 功能。
您可以使用 override 和 virtual 关键字执行此操作。
不知道起什么标题,希望有经验的whosebug.com网友改进。
假设我们有 class A
class A {
void hello(){ cout << "i'm an A" << endl; }
}
及其sub-class B
class B: public A {
void hello(){ cout << "i'm a B" << endl; }
}
然后我们在程序的某处做了
A* array[2];
array[0] = new A;
array[1] = new B;
array[0]->hello(); // output: "i'm an A"
array[1]->hello(); // output: "i'm a B"
为什么 array[1].hello();
不输出 I'm a B
,因为我们为 base-class 指针实例化了 B
object?以及如何实现它?
您必须使 hello
成为虚函数:
class A {
virtual void hello() { cout << "i'm an A" << endl; }
};
class B : public A {
virtual void hello() override { cout << "i'm a B" << endl; } // 1)
};
这告诉编译器实际函数不应该由静态类型(指针或引用的类型)决定,而是由对象的动态(运行-时间)类型决定。
1) override
关键字告诉编译器检查该函数是否实际上覆盖了基 class 中的 hello
函数(有助于例如捕获拼写错误或参数类型)。
这里有几个变化:
make function hello in class A, a virtual
and public:
因为默认是 private
class A {
public:
virtual void hello(){ cout << "i'm an A" << endl; }
};
同样在classB
virtual
class B: public A {
virtual void hello(){ cout << "i'm a B" << endl; }
};
由于您在class B 中继承了class A,派生class B 将调用Base class 中的函数。您需要覆盖 class B 中的函数,因为您想要更改基础 class 功能。
您可以使用 override 和 virtual 关键字执行此操作。