aar*_*man 0 c++ pointers reference
在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;
}
Run Code Online (Sandbox Code Playgroud)
为什么你不能用像Child & c()传入测试函数的引用做同样的事情.我问这个,因为指针和引用往往表现相似
这是因为你的榜样选择不当.你通常不应该裸露new在用户代码周围.
以下示例演示了相似之处:
struct Base { virtual ~Base() {} };
struct Derived : Base { };
void foo(Base *);
void bar(Base &);
int main()
{
Derived x;
foo(&x); // fine
bar(x); // fine and even better
}
Run Code Online (Sandbox Code Playgroud)
(另请注意,父子关系与基础派生关系非常不同.后者是"is-a",前者是"支持直到25".)