【问题标题】:Why should I use const and & while declaring class in function? [duplicate]为什么在函数中声明类时要使用 const 和 &? [复制]
【发布时间】:2017-09-09 09:23:07
【问题描述】:

我完全不明白这一点。我只知道;如果我不这样写

void samplefunctionname(const randomclass &classmember) {
  //code goes here...
}

该函数会将类成员中的所有信息复制到自身。所以对记忆不好。也许我只想写我选择的类成员变量,但如果我不写 const 和 & 它只会写所有信息。

但是这些家伙到底在做什么呢?为什么类应该是 const 等。

【问题讨论】:

    标签: c++ function class memory constants


    【解决方案1】:

    在函数中声明类时为什么要使用 const 和 &?

    为了避免复制整个类。当您使用const& 时,您通过引用传递对象,这根本不会复制任何数据。

    【讨论】:

    • 不会复制任何数据
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-05
    • 1970-01-01
    • 2018-07-03
    • 2011-03-09
    • 2014-10-15
    • 2020-04-11
    相关资源
    最近更新 更多