簡體   English   中英

為什么std :: nullptr_t在C ++中不能與std :: cout一起使用?

[英]Why does not std::nullptr_t work with std::cout in C++?

我了解了std::nullptr_t ,它是空指針文字的類型, nullptr

然后我做了一個小程序:

#include <iostream>

int main() 
{
    std::nullptr_t n1; 
    std::cout<<n1<<endl;
    return 0;
} 

這里, nullptr_t是數據類型, n1是可變的,我正在嘗試打印變量的值。 但是,編譯器給出了一個錯誤:

prog.cpp: In function 'int main()':
prog.cpp:6:11: error: ambiguous overload for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'std::nullptr_t')
  std::cout<<n1<<endl;

為什么std::nullptr_t在C ++中不能與std::cout一起使用? 我錯在哪里?

operator<< for output streams有多個不同類型指針的重載, 但不是std::nullptr_t 1 這意味着編譯器無法確定要調用哪個重載,因為任何接受指針的重載都同樣好。 (例如,它接受用於C風格字符串的char const * ,以及void const * ,它將輸出原始指針值。)

修復此問題的一個選項是定義自己的重載,強制使用void const * overload:

std::ostream & operator<<(std::ostream &s, std::nullptr_t) {
    return s << static_cast<void *>(nullptr);
}

或者讓它做其他事情:

std::ostream & operator<<(std::ostream &s, std::nullptr_t) {
    return s << "nullptr";
}

筆記:

  • 1正如注釋中所指出的,在C ++ 17中有一個重載接受std::nullptr_t ,所以如果你使用一致的C ++ 17實現,這將不再是一個問題。
  • endl需要std:: -qualification - 但無論如何你應該在這里使用'\\n' (當你需要刷新流時, std::endl只是個好主意。)

暫無
暫無

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

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