从字符到字符编译器的转换无效错误

Invalid conversion from char to char compiler error

本文关键字:字符 无效 错误 转换 编译器      更新时间:2023-10-16
void Emplyee::setname (char Name[50])
{ name [50] = Name [50] ;      }
void Emplyee::setadress (char Adress [100])
{  adress [100] = Adress [100] ;      }
Number.setname (Name [50]);   \ Error in this Line
Number.setadress (Adress [100]);  \ Error in this Line

您已将函数参数声明为类型 char[],但您正在使用 char 数组的元素调用该函数,该元素的类型为 char .仅使用NameAdress调用函数

在数组的使用方面,您的代码还有其他问题,但这将修复有问题的编译器错误。它不会解决您将要看到的其他问题......

我会指出其中的一些...

void Emplyee::setname (char Name[50])
{ 
    name [50] = Name [50] ;   // this line won't do what you think it does. (look at strcpy...)
       //  ^           ^
       //  |-----------|------ also, subscript out of bounds...
}

此外,地址也一样。

char name[50]; // declares an array of chars, called name, with a size of 50 elements
// ...
char c = name[50]; // access the 50th element (out of bounds, btw) of the name array, and assign to c. has nothing to do with size.
name [50] = Name [50] ;

这不会做你认为它做的事情,它会用 Name 的元素 51 覆盖名称的元素 51。它不会复制整个数组,只复制一个元素。这也可能是缓冲区溢出错误。

这整个代码表明你不理解数组,我认为你现在使用 std::string 的麻烦会更少。这是一个基于您编写的内容的简单示例:

#include <string>
class Emplyee{
    std::string address, name;
public:
    void setname (std::string Name)
    { name = Name ;      }
    void setadress (std::string Adress)
    {  adress = Adress ;      }
};
Emplyee Number;
Number.setname ("AAAA");
std::string Address = "Your address here";
Number.setadress (Address); 

最后,我想说的是,注释是//而不是 \\,为了保持一致性,最好尽可能尝试并尊重语言的命名约定。