今天我在使用参考文献时看到了非常奇怪的事情.
只是一个简单的例子:
#include <iostream>
struct Base {
enum Type {
FOO = 0,
BAR = 1
};
virtual ~Base() {}
virtual Type type() const = 0;
int value_;
};
struct Foo : Base {
Foo() { value_ = 33; }
virtual Type type() const { return FOO; }
};
struct Bar : Base {
Bar() { value_ = 44; }
virtual Type type() const { return BAR; }
};
int main() {
Foo foo;
Bar bar;
Base & b = foo;
std::cout << b.type() << ", " << b.value_ << "\n";
b = bar;
std::cout << b.type() << ", " << b.value_ << "\n";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
您认为输出是什么?看到它时我真的很惊讶:
0, 33
0, 44
Run Code Online (Sandbox Code Playgroud)
在VS 2010上测试,mingw 4.6,gcc 4.3.那么,可能知道这个魔法的秘密?
引用类似于C++中的指针,有两个重要的例外(除了语法):
所以,当你打电话时b = bar,你没有重新分配参考; 您正在bar为引用的对象赋值b; 在这种情况下,你要分配的值bar来foo.因此,在第二行,你将有一个Foo与对象value_的44.正是你的输出说的.