【问题标题】:error: could not convert 'p1' from 'Person (*)()' to 'Person'错误:无法将 'p1' 从 'Person (*)()' 转换为 'Person'
【发布时间】:2014-08-13 13:29:10
【问题描述】:

我明白了

error: could not convert 'p1' from 'Person (*)()' to 'Person'

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

我也收到 2 个警告

warning: converting to non-pointer type 'char' from NULL [-Wconversion-null]|

在默认构造函数中

warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]| 

当我创建 Person p2

这是我的代码

#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;
}

【问题讨论】:

    标签: c++


    【解决方案1】:

    你遇到了most vexing parse

    Person p1(); 声明了一个名为 p1 的函数,它返回一个 Person 并且不接受任何参数。如果你想默认构造一个名为p1Person 对象,只需说Person p1;

    【讨论】:

      【解决方案2】:

      第一个警告是因为您尝试将 NULL 分配给作为字符的性别。

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

      【讨论】:

      • 好的,我解决了第一个警告,但我不知道在第二个中该怎么做,如果我将 char* const 我仍然得到同样的错误
      • char* const 和 char const* 是两个不同的东西,见这里:stackoverflow.com/questions/4949254/…
      猜你喜欢
      • 1970-01-01
      • 2020-03-16
      • 2020-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-21
      相关资源
      最近更新 更多