我正在尝试为数组实现我自己的交换函数,但它似乎存在转换问题。 我不知道。 如果这个问题太愚蠢,请原谅我。
这是源代码:
x_quiz3.h
#include<array>
using namespace std;
void swap_arr_element(array<int,5> &arr, int index1, int index2){
int temp{arr.at(index1)};
arr.at(index1) = arr.at(index2);
arr.at(index2) = temp;
}
void start_x_quiz3(){
array arr{1,2,4,3,5};
swap_arr_element(arr, 2, 3);
for (auto &i : arr){
cout << i << " ";
}
}
主要.cpp:
#include <iostream>
#include "x_quiz3.h"
int main()
{
start_x_quiz3();
return 0;
}
错误信息:
||=== Build: Debug in chapter6 (compiler: GNU GCC Compiler) ===|
/home/lewisluk/CodeBlocksProjects/tutorials/quizs/chapter6/x_quiz3.h||In function ‘void swap_arr_element(std::array<int, 5>&, int, int)’:|
/home/lewisluk/CodeBlocksProjects/tutorials/quizs/chapter6/x_quiz3.h|8|error: conversion to ‘std::array<int, 5>::size_type {aka long unsigned int}’ from ‘int’ may change the sign of the result [-Werror=sign-conversion]|
/home/lewisluk/CodeBlocksProjects/tutorials/quizs/chapter6/x_quiz3.h|9|error: conversion to ‘std::array<int, 5>::size_type {aka long unsigned int}’ from ‘int’ may change the sign of the result [-Werror=sign-conversion]|
/home/lewisluk/CodeBlocksProjects/tutorials/quizs/chapter6/x_quiz3.h|9|error: conversion to ‘std::array<int, 5>::size_type {aka long unsigned int}’ from ‘int’ may change the sign of the result [-Werror=sign-conversion]|
/home/lewisluk/CodeBlocksProjects/tutorials/quizs/chapter6/x_quiz3.h|10|error: conversion to ‘std::array<int, 5>::size_type {aka long unsigned int}’ from ‘int’ may change the sign of the result [-Werror=sign-conversion]|
||=== Build failed: 4 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
最佳答案
at
的参数函数是 size_type
,它是一个 unsigned 类型。
交换函数的索引参数是int
,它是一个有符号类型。
编译器说它不能安全地从有符号类型转换为无符号类型(它不能,想想如果你提供负索引会发生什么)。
简单的解决方案是使交换函数索引参数也无符号,最好使用size_t
类型:
void swap_arr_element(array<int,5> &arr, size_t index1, size_t index2){ ... }
关于c++ - cpp新手问题: error: conversion to ‘std::array<int, 5>::size_type {aka long unsigned int}’ from ‘int’ may change the sign of the result,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59662985/