Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/macos/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 错误:无法转换';p1和x27;从';个人(*)和#x27;至';人';_C++ - Fatal编程技术网

C++ 错误:无法转换';p1和x27;从';个人(*)和#x27;至';人';

C++ 错误:无法转换';p1和x27;从';个人(*)和#x27;至';人';,c++,C++,我明白了 每当我使用默认构造函数(当我创建Person p1时),我知道这是因为我使用的是字符数组,但我必须使用它,我不能使用字符串 我还收到了两条警告 error: could not convert 'p1' from 'Person (*)()' to 'Person' 在默认构造函数中 warning: converting to non-pointer type 'char' from NULL [-Wconversion-null]| 当我创建Person p2时 这是我的密码

我明白了

每当我使用默认构造函数(当我创建Person p1时),我知道这是因为我使用的是字符数组,但我必须使用它,我不能使用字符串

我还收到了两条警告

error: could not convert 'p1' from 'Person (*)()' to 'Person'
在默认构造函数中

warning: converting to non-pointer type 'char' from NULL [-Wconversion-null]|
当我创建Person p2时

这是我的密码

warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]| 
#包括
#包括
#包括
#包括
使用名称空间std;
班主任{
私人:
字符*名称;
性别;
智力年龄;
公众:
人();
人(字符*,字符,整数);
朋友无效打印信息(个人);
};
Person::Person()
:name(NULL)、gender(NULL)、age(0)//这将导致第一个警告
{
}
Person::Person(字符*n、字符g、整数a)
:姓名(n)、性别(g)、年龄(a)
{
}
无效打印信息(个人p){
你可能会遇到麻烦

Person p1();
声明一个名为
p1
的函数,该函数返回一个
Person
且不带任何参数。如果要默认构造一个名为
p1
Person
对象,只需说
Person p1;

,您就遇到了


Person p1();
声明一个名为
p1
的函数,该函数返回一个
Person
且不带任何参数。如果您想默认构造一个名为
p1
Person对象,只需说
Person p1;
第一个警告出现,因为您试图将NULL赋值给字符性别


第二个原因是您将常量字符指针指定给对象中的非常量字符指针。使用
char const*
(或
const char*
)作为指针类型是消除此警告的方法之一。使用char*const没有帮助,因为它基本上意味着常量指针指向可修改的字符串(即,您不能更改指针,但可以更改字符串)当您给它一个字符串常量时,情况并非如此。

第一个警告出现,因为您试图为字符的性别赋值NULL


第二个原因是您将常量字符指针指定给对象中的非常量字符指针。使用
char const*
(或
const char*
)作为指针类型是消除此警告的方法之一。使用char*const没有帮助,因为它基本上意味着常量指针指向可修改的字符串(即,您不能更改指针,但可以更改字符串)当你给它一个字符串常量时,情况就不是这样了。

好的,我解决了第一个警告,但我不知道在第二个警告中该怎么做,如果我做了char*const,我仍然得到相同的errorchar*const和char-const*是两个不同的东西,请看这里:好的,我解决了第一个警告,但我不知道在第二个警告中该怎么做,如果我做了char*const我仍然得到相同的错误char*const和char-const*是两个不同的东西,请看这里:
#include <iostream>
#include <string>
#include <stdlib.h>
#include <stdio.h>
using namespace std;

class Person{
   private:
    char* name;
    char gender;
    int age;
   public:
    Person();
    Person(char*, char, int);
    friend void printInfo(Person);
};

Person::Person()
:name(NULL), gender(NULL), age(0) // this results in the first warning
{
}
Person::Person(char* n, char g, int a)
:name(n), gender(g), age(a)
{
}
void printInfo(Person p){
 cout << "Name: " << p.name << endl;
 cout << "Age: " << p.age << endl;
 cout << "Gender: " << p.gender << endl;
}

int main()
{
Person p1(); // this results in an error
printInfo(p1);

Person p2("Max", 'm', 18); // this results in the second warning
printInfo(p2);

return 0;
}