非const引用作为函数参数

时间:2013-05-25 10:02:35

标签: c++ reference const

我写了以下代码。我将两个函数增加和constincrease作为输入,它将类引用作为输入。 constincrease将其视为常量,而增加更简单并允许对其进行修改。

我不明白为什么行无法编译

increase(fun()); //此行无法编译

..我知道临时对象是常量,因此上面的行可能会失败,因为增加需要非const引用。但是,如果我们看到另一行代码传递

increase(x3);

点是上面一行通过的原因,但其他东西无法正确编译。

class X{
      public:
          int i ;
      };

X fun(){
      return X();
      }

void  increase(  X & p ) 
      {
        cout<< "\n non-const-increase called ";
    p.i++;
      }

void  constincrease(  const X & p ) 
      {
        cout<< "\n const-increase called ";                   
        // this function p is const so   p.i++; is wrong ...
      }

int main(int argc, char *argv[])

{

    X x3;
    x3.i=9;
    increase(x3);  // this line passes compilation 
    constincrease(x3); // const-increase alwasy passes

    increase(fun()); // this line fails to compile 
    constincrease(fun()); // const -increase passes
    system("PAUSE");
    return EXIT_SUCCESS;
}

0 个答案:

没有答案
相关问题