为什么编译器不断警告我从“int”缩小到“uint8”
Why is compiler keep warning me that narrowed from `int` to `uint8`?
我再次检查了一遍,我确定我没有uint8
投int
隐含在我的代码中,向前或向后
// main.cpp
#include <iostream>
using std::cout, std::endl;
using uint8 = unsigned char;
struct Vector {
uint8 x, y, z;
Vector operator+(const Vector& v) const {
return Vector{this->x + v.x, this->y + v.y, this->z + v.z};
};
void operator+=(const Vector&);
void operator-(const Vector&) const;
Vector operator-=(const Vector&);
Vector operator*(const uint8 scaler) const;
Vector Corss(const Vector&, const Vector&) const;
void Corss(const Vector&);
Vector Dot(const Vector&, const Vector&) const;
void Dot(const Vector&);
};
std::ostream& operator<<(std::ostream& os, Vector& vec) {
return os << "(" << (unsigned)vec.x << "," << (unsigned)vec.y << ","
<< (unsigned)vec.z << ")";
}
int main() {
Vector v1{1, 2, 3};
Vector v2{1, 1, 1};
Vector v3 = v1 + v2;
cout << v1 << endl;
cout << v2 << endl;
cout << v3 << endl;
}
提示:
$g++ main.cpp -std=c++17 -O0 -g -Wall -Wextra
main.cpp: In member function 'Vector Vector::operator+(const Vector&) const':
main.cpp:10:27: warning: narrowing conversion of '(((int)((const Vector*)this)->Vector::x) + ((int)v.Vector::x))' from 'int' to 'uint8 {aka unsigned char}' inside { } [-Wnarrowing]
return Vector{this->x + v.x, this->y + v.y, this->z + v.z};
~~~~~~~~^~~~~
main.cpp:10:42: warning: narrowing conversion of '(((int)((const Vector*)this)->Vector::y) + ((int)v.Vector::y))' from 'int' to 'uint8 {aka unsigned char}' inside { } [-Wnarrowing]
return Vector{this->x + v.x, this->y + v.y, this->z + v.z};
~~~~~~~~^~~~~
main.cpp:10:57: warning: narrowing conversion of '(((int)((const Vector*)this)->Vector::z) + ((int)v.Vector::z))' from 'int' to 'uint8 {aka unsigned char}' inside { } [-Wnarrowing]
return Vector{this->x + v.x, this->y + v.y, this->z + v.z};
~~~~~~~~^~~~~
$./a.out
(1,2,3)
(1,1,1)
(2,3,4)
表达式this->x + v.x
&c.中的每个项都会自动加宽为一个int
,并且该表达式的类型是int
。这是因为+
的论据比int
窄。然后,编译器会向您发出警告,因为您正在初始化类型比 int
窄Vector
元素。
这是C++生活中的事实。你可以得到同样的效果,比如
auto a = 'a' + 'b';
a
是一种int
类型。
相关文章:
- 为什么在全局范围内使用"extern int a"似乎不行?
- int(c) 和 c-'0' 之间的区别。C++
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 为什么野牛仍在使用"int yylex(void)",却找不到"int yylex(YYS
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 是否可以从int转换为enum类类型
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 'short int'持有的值溢出,但"自动"不会溢出?
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 调用'begin(int [n])'没有匹配函数
- 没有显式声明的int[]中的foreach
- 在c++中访问int到类对象的映射时出错
- 为什么我无法更改"set<set>"循环中的值<int>
- 长 长 int 不要 长 int 好
- C++程序在循环后给出奇怪的int值
- 错误:无法将'uint8* {aka unsigned int*}'转换为"常量emxArray_uint8_T*"?
- 为什么编译器不断警告我从“int”缩小到“uint8”
- 将无符号int(uint8,16,32)存储在变量中