×

Loading...
Ad by
  • 最优利率和cashback可以申请特批,好信用好收入offer更好。请点链接扫码加微信咨询,Scotiabank -- Nick Zhang 6478812600。
Ad by
  • 最优利率和cashback可以申请特批,好信用好收入offer更好。请点链接扫码加微信咨询,Scotiabank -- Nick Zhang 6478812600。

好象是可以的, 见内

const int x; // constant int
x = 2; // illegal - can't modify x

const int* pX; // changeable pointer to constant int
*pX = 3; // illegal - can't use pX to modify an int
pX = &someOtherIntVar; // legal - pX can point somewhere else

int* const pY; // constant pointer to changeable int
*pY = 4; // legal - can use pY to modify an int
pY = &someOtherIntVar; // illegal - can't make pY point anywhere else

const int* const pZ; // const pointer to const int
*pZ = 5; // illegal - can't use pZ to modify an int
pZ = &someOtherIntVar; // illegal - can't make pZ point anywhere else
Report

Replies, comments and Discussions:

  • 工作学习 / IT技术讨论 / C++ 问题请教
    box( std::string const& input_line );

    能该为 box( std::string const * input_line ); 吗? 有什么不同吗? 我理解两者都将input_line 声明为 string 的指针呀.

    正在学习, 请教.
    • reference was different with pointer. When you call this function, it would be different.
      • There is a bit difference
        Both pass an address of a string variable. The call will be different

        for example
        string str_line;

        If you use the definition box( std::string const& input_line ), the call is box(str_libne) while for box( std::string const* input_line ), the call will be box(&str_line). They will archieve the same functionality
    • 说明为常数引用参数意味在函数体里面不能为它赋值,这是主要的。
      • box( std::string const * input_line ); input_line 是否也是常数呢? 在函数体里面能为它赋值吗?
        • 指针可以说明为常量型吗?我还真没用过
          • 好象是可以的, 见内
            const int x; // constant int
            x = 2; // illegal - can't modify x

            const int* pX; // changeable pointer to constant int
            *pX = 3; // illegal - can't use pX to modify an int
            pX = &someOtherIntVar; // legal - pX can point somewhere else

            int* const pY; // constant pointer to changeable int
            *pY = 4; // legal - can use pY to modify an int
            pY = &someOtherIntVar; // illegal - can't make pY point anywhere else

            const int* const pZ; // const pointer to const int
            *pZ = 5; // illegal - can't use pZ to modify an int
            pZ = &someOtherIntVar; // illegal - can't make pZ point anywhere else
    • 两者功能一样,只是表现形式不同。
      如果写成box( std::string * const input_line ); 就不同了。这表示指针本身不能改变。到底使用指针还是引用,要看你的爱好。用指针时你要多敲一个字母。仅此而已。
      • Pointers and references are quite different, read more books please.
      • 还可以写成 box( std::const string * const input_line ); 对吗? 学到现在, 还真没发现它们有本质区别.