2009-09-04 48 views
1

有人可以解释为什么下面的代码无效吗?是否因为名为d的变量的偏移量与名为b的变量不同?调用函数并将参考指针传递给派生类型时出错

class Base { public: int foo; }; 

class Derived : public Base { public: int bar; }; 

int DoSomething(Base*& b) { return b->foo; } 

Base* b = new Derived; 
Derived* d = new Derived; 

int main() 
{ 
    DoSomething(d); 
} 

这是错误the online Comeau C++ compiler给出:

"ComeauTest.c", line 12: error: a reference of type "Base *&" (not const-qualified) 
      cannot be initialized with a value of type "Derived *" 
    DoSomething(d); 
       ^

这是一个类似的问题,但不同的是,因为在我的例子,我声明d为指针类型:Passing references to pointers in C++

注当我通过bDoSomething时,这确实会编译。

回答

10

想象一下,你可以做到这一点。引用不是const,所以可以将DoSomething分配给指针,并且在调用者中可见。特别是,在DoSomething内部,我们可以将指针改为指向不是Derived实例的东西。如果调用者在我们返回之后尝试对指针执行派生特定的事情,它将会爆炸。

3

这与偏移无关。请注意,Derived在您的示例中既有foo也有bar作为字段(并且是的,它们将具有不同的偏移量,但这与此无关)。

如果允许这样做,它将不会是类型安全的。考虑以下代码:

class Base { public: int foo; }; 

class Derived1 : public Base { public: int bar; }; 

class Derived2 : public Base { public: float baz; }; 

void DoSomething(Base*& b) { b = new Derived2; } 

Derived1* d = new Derived1; 
DoSomething(d); // d is of type Derived1*, but now points to object 
       // of incompatible type Derived2 
3

假设DoSomething的是这样定义的:

int DoSomething(Base*& b) { b = new Base; } 

哎呀,现在主要在调用DoSomething的,d结束在基本指向,而不是在所有派生。

相关问题