繁体   English   中英

cpp 新手问题:错误:转换为 &#39;std::array<int, 5> ::size_type {aka long unsigned int}&#39; from &#39;int&#39; 可能会改变结果的符号

[英]cpp newbie question: error: conversion to ‘std::array<int, 5>::size_type {aka long unsigned int}’ from ‘int’ may change the sign of the result

我正在尝试为数组实现我自己的交换函数,但它似乎有转换问题。 我没有任何线索。 如果这个问题太愚蠢,请原谅我。

这是源代码:

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 ,它是一个无符号类型。

交换函数的索引参数是int ,它是一种有符号类型。

编译器说它不能安全地从有符号类型转换为无符号类型(它不能,想想如果你提供负索引会发生什么)。

简单的解决方案是使交换函数索引参数也无符号,最好使用size_t类型:

void swap_arr_element(array<int,5> &arr, size_t index1, size_t index2){ ... }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM