🔴 传值传出来的那个,只剩基类那一半
(本条路线统一用 g++ -std=c++17 -O0 -Wall 编译)同一个对象,一个传值一个传引用:
#include <iostream>
struct Shape {
virtual int area() const { return 0; }
virtual ~Shape() = default;
};
struct Rect : Shape {
Rect(int w, int h) : w_(w), h_(h) {}
int area() const override { return w_ * h_; }
private:
int w_, h_;
};
/* 传值:派生的那半截被切掉了,只剩基类那部分 */
int by_value(Shape s) { return s.area(); }
/* 传引用:还是原来那个对象 */
int by_ref(const Shape &s) { return s.area(); }
int main() {
Rect r(3, 4);
std::cout << by_value(r) << "/" << by_ref(r) << "/" << r.area() << "\n";
return 0;
}
全部评论