在C++中这一点也适用指针指针与在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()
传递到测试函数的引用。我问这一点,因为指针和引用往往表现相似
什么是 “一回事” ? – 2013-05-28 06:49:01
@ H2CO3如果你通过测试函数的引用,它不会编译 – aaronman
@aaronman Euh,*你为什么*期望它编译?引用不是指针... – 2013-05-28 06:51:22