c++ - 引用抽象类赋值问题

标签 c++ reference abstract-class

关于问题“reference to abstract class”,我编写了以下示例:

#include <iostream>
#include <vector>

class data
{
  public:
    virtual int get_value() = 0;
};

class data_impl : public data
{
  public:
    data_impl( int value_ ) : value( value_ ) {}
    virtual int get_value() { return value; }
  private:
    int value;
};

class database
{
  public:
    data& get( int index ) { return *v[index]; }
    void  add( data* d ) { v.push_back( d ); }
  private:
    std::vector< data* > v;
};

int main()
{
    data_impl d1( 3 );
    data_impl d2( 7 );

    database db;
    db.add( &d1 );
    db.add( &d2 );

    data& d = db.get( 0 );
    std::cout << d.get_value() << std::endl;
    d = db.get( 1 );
    std::cout << d.get_value() << std::endl;

    data& d_ = db.get( 1 );
    std::cout << d_.get_value() << std::endl;
    d_ = db.get( 0 );
    std::cout << d_.get_value() << std::endl;

    return 0;
}

令我惊讶的是,该示例打印:

3
3
7
7

看起来引用分配的工作方式与我的预期不同。我希望:

3
7
7
3

你能指出我的错误是什么吗?

谢谢!

最佳答案

data& d = db.get( 0 );
std::cout << d.get_value() << std::endl;
d = db.get( 1 );
std::cout << d.get_value() << std::endl;

第一条语句是一个引用初始化,而第三条语句是一个slicing assignment。 .

您不能重新安排引用。

干杯,

关于c++ - 引用抽象类赋值问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7344739/

相关文章:

c# - 在数据迁移中传输大数据

c++ - 自定义 std::set 比较器 - 不匹配调用 [...]

java - 如何在 Eclipse 中使用 JAR 中的类

c++ - 重载抽象虚方法返回模板参数 T& 作为具体参数 short*&

java - 抽象类需要访问子类属性

c++ - 对抽象类和 `decltype` 的左值引用

c++ - MFC GetLastError 返回 5(访问被拒绝)

c++ - Fortran 64 位十六进制 BOZ

c++ - 返回一个 const 引用和非 const 成员函数调用

java - Java中抽象类的使用