簡體   English   中英

為什么我可以定義一個在某些參數的頂級常量中有所不同的函數?

[英]Why I can define a function that differs in the top-level constness of some of its paramters?

通常,函數和類在頭文件中聲明,並在某些源文件中定義,例如,我有此函數,它僅對int進行常量引用並返回bool值,以確定該參數是偶數還是奇數:

因此,在我的標題odd_even.h我寫了:

    bool is_even(const int& x); // I used const ref. to avoid copy and unintentional modification of the argument.

並且在源odd_even.cpp

bool is_even(int& x) { 
    if (x = 1024) // some unintentional assinemnt (==) though modern compilers detect it.
        ; //some statement here
    //x = 1024; // or here another unintentional modification
    return !(x % 2) ? true : false; 
}

和驅動程序:

int main(){

    int a{ 17 };
    std::cout << (a) << std::endl;

    std::cout << std::boolalpha << is_even(a) << endl;

    std::cout << (a) << std::endl;

    std::cout << std::endl;
}

如您所見,函數is_even定義無意間修改了參數,並且我程序的客戶端沒有意識到,只要聲明使用const引用int的函數,該函數就不會修改參數。

那么,關於此錯誤的解決方法是否可以防止此類錯誤?

這不應該作為編譯證明這里

當參數是指針或引用類型時,C ++允許cv限定符進行重載,因此它是錯誤名稱的一部分。

這里沒有top-level const

bool is_even(const int& x); // 1
bool is_even(int& x); // 2

1和2以上是完全不同的簽名:1是一個對int進行常量引用的函數。 請記住,這里的constlow-level而不是top-level還要記住,引用沒有頂級const是因為它們已經是常量。

在您的示例中,它編譯並運行正常,因為您要傳遞與簽名2相關的非常量對象。但是,如果傳遞r值,則它將無法鏈接。 例如:

std::cout << is_even(77) << std::endl; // link will fail because the 1 is not defined.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM