0

在 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()传递给测试函数的引用做同样的事情。我问这个是因为指针和引用的行为往往相似

4

3 回答 3

5

这是因为您的示例选择不当。您通常不应该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
 }

(另请注意,父子关系与基派生关系非常不同。后者是“is-a”关系,前者是“supports-till-25”关系。)

于 2013-05-28T06:51:43.153 回答
3
Derived & d() 

是一个函数声明(返回类型 Derived& 并且没有输入参数)而不是对象实例化。这是 C++ 的 MVP(http://en.wikipedia.org/wiki/Most_vexing_parse

使用这个语法

Derived d;

这么称呼

test(d);
于 2013-05-28T07:14:27.527 回答
3

Derived & d1();不做你假设的事情。

看看这里

[10.2] List x 有什么区别吗?和列表 x();? 很大的不同!

假设 List 是某个类的名称。然后函数 f() 声明了一个名为 x 的本地 List 对象:

void f()
{
  List x;     // Local object named x (of class List)
  ...
}

但是函数 g() 声明了一个名为 x() 的函数,它返回一个 List:

void g()
{
  List x();   // Function named x (that returns a List)
  ...
}
于 2013-05-28T07:17:20.670 回答