gpt4 book ai didi

c++ - 为什么编译器不断警告我从 `int` 缩小到 `uint8`?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:17:26 25 4
gpt4 key购买 nike

我检查了一遍又一遍,我确定我没有将 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 更窄。然后您的编译器会向您发出警告,因为您正在初始化 Vector 元素,其类型比 int 窄。

这是 C++ 生活中的一个事实。你用类似的东西得到同样的效果

auto a = 'a' + 'b';

a 是一个 int 类型。

关于c++ - 为什么编译器不断警告我从 `int` 缩小到 `uint8`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48114723/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com