【问题标题】:what does it mean when you have "const" after your function name and input? [duplicate]当你的函数名和输入后面有“const”是什么意思? [复制]
【发布时间】:2011-11-23 01:44:20
【问题描述】:

可能重复:
What does const mean following a function/method signature?

继续笑我,但是函数后面的const表示什么?

int someFunc() const{  //<<----notice the const
    //insert code  blah...
}

如果我想要一个 const int 的返回类型,我不会写

const int someFunc(){
    //code....
}

【问题讨论】:

  • 我会说它也是重复的。我真的不知道我在寻找什么,这是一种晦涩难懂的东西
  • 顺便说一下,返回类型intconst int 100% 相同。编译器会忽略标量返回类型的顶级 consts。
  • 这实际上是有道理的,谢谢@FredOverflow

标签: c++


【解决方案1】:

这意味着函数不能改变任何成员变量。

class A {
void Func() const
{
  ++mI; // compiler error
}
int mI;
};

【讨论】:

    【解决方案2】:

    这意味着该函数不会改变对象属性,除了“可变”

    【讨论】:

    • 感谢您提供的信息,我觉得@axon 的回答对于像我这样的菜鸟来说更容易理解:D。再次感谢
    【解决方案3】:

    有关详细定义,请参阅this。这是一个非常好的。

    【讨论】:

    • 实际上我只是在阅读:D 谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-05
    • 2020-04-07
    • 2015-09-29
    • 2011-05-02
    • 2011-03-09
    • 2015-02-01
    相关资源
    最近更新 更多