2013-05-28 38 views
0

在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()传递到测试函数的引用。我问这一点,因为指针和引用往往表现相似

+2

什么是 “一回事” ? – 2013-05-28 06:49:01

+0

@ H2CO3如果你通过测试函数的引用,它不会编译 – aaronman

+0

@aaronman Euh,*你为什么*期望它编译?引用不是指针... – 2013-05-28 06:51:22

回答

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 
} 

(还要注意的是父 - 子的关系是从一个基衍生的关系非常不同,后者是一个“是”的一个,前者。是一个“支持免耕-25”之一。)

+3

“支持至25”?我想的更糟。 –

+0

我不认为这编译 – aaronman

+0

我不是愚蠢的,但什么是亲子关系在这里?我只用于基础派生。对不起,如果这是愚蠢的,但我无法抗拒 –

3
Derived & d() 

是一个函数声明(导出&返回类型和不具有输入参数),而不是对象实例化。这是C++的最有价值球员(http://en.wikipedia.org/wiki/Most_vexing_parse

使用这种语法

Derived d; 

呼叫作为这样

test(d); 
+0

实际上并不是最令人头疼的解析,而是让人烦恼。 –

3

Derived & d1();不会做你认为是什么。

看一看here

[10.2]有清单X之间的任何差别;和List x();? 有很大的区别!

假设List是某个类的名字。然后,函数f()声明名为x本地列表对象:)

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

但是函数g()声明了一个名为x(函数返回一个列表:

void g() 
{ 
    List x(); // Function named x (that returns a List) 
    ... 
}