【问题标题】:Error calling function and passing a reference-to-pointer with a derived type调用函数并使用派生类型传递引用指针时出错
【发布时间】:2009-09-04 18:46:02
【问题描述】:

有人可以解释为什么以下代码无效吗?是不是因为名为@9​​87654323@ 的变量的偏移量与名为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++

请注意,当我将 b 传递给 DoSomething 时,它会编译。

【问题讨论】:

    标签: c++ pointers polymorphism reference


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      这与偏移无关。请注意,您的示例中的 Derived 同时具有 foobar 作为字段(是的,它们将具有不同的偏移量,但这在这里无关紧要)。

      如果允许,它就不是类型安全的。考虑这段代码:

      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; }
        

        糟糕,现在当 main 调用 DoSomething 时,d 最终指向 Base 而不是 Derived。

        【讨论】:

          猜你喜欢
          • 2014-04-18
          • 1970-01-01
          • 1970-01-01
          • 2021-05-25
          • 1970-01-01
          • 1970-01-01
          • 2018-01-23
          • 1970-01-01
          相关资源
          最近更新 更多