我希望auto關鍵字從初始化器中推斷出變數的型別一次,并在整個代碼中保持該型別。令我驚訝的是,我的編譯器 ( g 9.3.0) 允許我更改它的型別并且它仍然有效。當我首先將變數用作 int 然后用作浮點數時,這對我來說是可以接受的。但是當我使用auto關鍵字宣告一個字串,然后為該變數分配一個浮點值時,編譯器不會拋出錯誤,也不會在浮點分配后列印該值。有人可以解釋為什么它允許首先將浮點值分配給字串變數嗎?編譯器每次都只接受新的賦值嗎?或者它是否拋出某種我無法捕捉到的例外?下面的代碼 -
#include <iostream>
int main()
{
auto x = '2';
std::cout << x << std::endl;
x = 3.0; // Why is this allowed?
std::cout << x << std::endl; // This won't print
return 0;
}
uj5u.com熱心網友回復:
為了向您展示發生了什么,我使用一些編譯時型別檢查擴展了示例:
#include <type_traits>
#include <iostream>
int main()
{
auto x = '2';
// decltype(x) is the type for variable x
// compare it at compile time with char type
static_assert(std::is_same_v<decltype(x), char>);
std::cout << x << std::endl;
x = 3.0; // Why is this allowed? because it does a narrowing conversion from double to char
// my compiler even gives this warning :
// main.cpp(11,6): warning C4244: '=': conversion from 'double' to 'char', possible loss of data
// type of x is still the same and it is still a char
static_assert(std::is_same_v<decltype(x), char>);
std::cout << static_cast<int>(x) << std::endl; // the cast is here to be able to print the actual value of the char
return 0;
}
uj5u.com熱心網友回復:
但是當我使用 auto 關鍵字來宣告一個字串時
你很困惑。這段代碼宣告了一個型別的變數char:
auto x = '2';
如果你想宣告一個字串,你必須使用雙引號:
auto x = "2";
的后續分配3.0將不會與此更改一起編譯。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/397890.html
上一篇:main()和function()中&array的不同值
下一篇:如何呼叫使用c 操作的方法
