🔴 传值传出来的那个,只剩基类那一半

👁️ 2 人浏览 💬 0 人评论 ❤️ 添加收藏

(本条路线统一用 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;
}
提交你的答案
请登录后提交答案。
去登录
代码编辑器
Ctrl + Enter 运行
本次输入:
输出:

                        
👩‍🏫
AI
💬 题目评论

全部评论