首頁  >  問答  >  主體

c++:举一个函数形参不能是引用的例子

这是一道习题

巴扎黑巴扎黑2715 天前723

全部回覆(3)我來回復

  • ringa_lee

    ringa_lee2017-04-17 12:06:31

    還真不容易找到這樣的例子。

    不過,在肯定會修改實參內容,而這種修改又不能影響原變數的情況下,比較適合不用引用吧。

    例如:

    bool read_file_in(string path, const string &file, string &out)
    {
        path += "/" + file;
        
        return read_file(path, out);
    }
    
    bool write_file_in(string path, const string &file, const string &in)
    {
        path += "/" + file;
        
        return write_file(path, in);
    }
    
    //...
    
    string path, data;
    
    //...
    read_file_in(path, "in.txt", data);
    write_file_in(path, "out.txt", data);
    

    在上面的範例中,第一個參數 path 是不是不用再引用比較好?

    回覆
    0
  • PHP中文网

    PHP中文网2017-04-17 12:06:31

    hibernake說的是對的,我的例子不合適

    回覆
    0
  • 迷茫

    迷茫2017-04-17 12:06:31

    當使用非常量引用,而實參是字面值、表達式、需要轉換的不同類型的物件時。如
    void swap(int &a,int &b);
    int a=2;
    double b=3.0;
    f(a,5);
    f(a+2,a );
    f(a,b);
    都不行。也不能用const int&,因為要交換a與b的值。

    回覆
    0
  • 取消回覆