在 c++ 中,这适用于指针
#include <iostream>
using namespace std;
struct Base {
virtual void base_method() {
cout << "this is the base\n";
}
};
struct Derived : public Base {
void base_method() {
cout << "this is the child\n";
}
};
void test(Base & b) {
b.base_method();
}
void test2(Base * b) {
b->base_method();
}
int main() {
Derived * d;
Derived & d1();
test2(d); //this works
test(d1); //this doesn't
return 0;
}
为什么你不能对Child & c()
传递给测试函数的引用做同样的事情。我问这个是因为指针和引用的行为往往相似