※ 引述《ro1234 ( 女子 月巴)》之銘言:
: 2.當函式的參數是reference to const type時,我們可以傳遞nonconst變數給它,而此
: 變數不需要經過轉換就可以使用
: (函式的參數如為reference to const,我們可以餵nonconst的變數給它)
: 3.當函式的參數是pointer to const type時,如果我們傳遞pointer to nonconst type
: 時,此pointer就需要先轉換成const pointer
: 但是我又作了實驗我將一般函式改成下式然後將 function tempalte刪除
: void test(const char*&,const char*&)
: {
: cout<<"Non-template"<<endl;
: }
: 但是如此一來兩個test function的呼叫都會產生錯誤
error: invalid initialization of non-const reference of type `const char*&' from an rvalue of type `char*'
error: in passing argument 1 of `void test(const char*&, const char*&)'
: 是因為在char*要轉型成 const char*&時
: char*->const char*->const char* & 其中 const char*這個位置會是一個tempory的值
: 因此無法讓reference 綁定 所以造成錯誤嗎?
: 那這樣不就跟結論的第二點產生矛盾
: 如果有說明不清的地方,請多多指正 謝謝各位
這個解釋沒有什麼問題, 跟第二點也不矛盾, 問題在於什麼是 reference to const type
首先什麼是 const type?
const int a;
const double b;
int c[10];
這三個都是 constant, assign to a, b, or c 都會 compile error
至於
int *d;
想當然爾不是 cosntant, 因為我們可以 d = NULL;
那麼
const int *e;
呢? 可以 e = NULL; 嗎? 可以耶! 為什麼 e 不是 constant 呢?
因為 e "points to" a constant
要 constant pointer 要寫
const int *const f;
int *const g;
這樣 g 雖然不指向 constant, 但是也是個 constant, a pointer constant
所以 reference to a pointer constant 要寫成
const int *const &h;
int *const &i;
把 test 改寫成
void test(const char* const&,const char* const&)
{
cout<<"Non-template"<<endl;
}
就可以了
--
All this will not be finished in the first 100 days.
Nor will it be finished in the first 1,000 days,
nor in the life of this Administration,
nor even perhaps in our lifetime on this planet.
But let us begin.
-- John F. Kennedy, Inaugural Address
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 128.36.232.45