【问题标题】:C++ Conversion Error: invalid conversion from short int* to short int [closed]C++ 转换错误:从 short int* 到 short int 的无效转换 [关闭]
【发布时间】:2014-06-29 15:46:59
【问题描述】:

我遇到了转换错误,实际上不知道如何解决。

我必须使用这些结构并且不知道如何访问 Date 结构的权利。 这是我的代码:

#include <iostream>
#include <string.h>

using namespace std;


struct Date {
 short year;
 short month;
 short day;
};

struct Stuff {
  Date birth;
};

struct ListElement {
  struct Stuff* person;          // Pointer to struct Stuff 
  struct ListElement* next;      // Pointer to the next Element
};

int main() {
 short birth_year;
 short birth_month;
 short birth_day;
 cin >> birth_year;
 cin >> birth_month;
 cin >> birth_day;


 ListElement* const start = new ListElement();
 ListElement* actual = start;

 actual->person = new Stuff();
 actual->person->birth.year = new short[sizeof(birth_year)]; // Conversion Error

delete start;
delete actual;
}

来自 GCC 的错误消息:

main.cpp: In function 'int main()':
main.cpp:35:29: error: invalid conversion from 'short int*' to 'short int' [-fpermissive]
  actual->person->birth.year = new short[sizeof(birth_year)]; // Conversion Error

【问题讨论】:

  • 错误信息在哪里?
  • 这段代码没有意义。为什么要尝试将数组分配给单个 short
  • Please read more thoroughly what your compiler tells you!你的标题是错误的。而且你不需要new() 顺便说一句。
  • 为您添加了来自 GCC 的错误消息。请阅读它,您的类型不匹配:short int != short int*! 始终编译时带有完整警告 (-Wall -Wextra -pedantic) 并处理所有警告!
  • delete actual; 也是一个错误,因为您已经删除了该指针。这个程序闻起来像“Java 程序员尝试 C++”

标签: c++


【解决方案1】:

您不能为actual-&gt;person-&gt;birth.year 分配内存,因为birth.year 不是指针。

您可以使用:actual-&gt;person-&gt;birth.year = 2014;
actual-&gt;person-&gt;birth.year = birth_year;

【讨论】:

    【解决方案2】:

    我认为你真正想做的是:

    actual-&gt;person-&gt;birth.year = birth_year;

    如果我错了,请阅读以下内容:

    你的结构中有:

    short year;

    但您试图将新返回的内容分配给year

    您应该这样做 short* year; 并动态处理它(永远不要忘记取消分配它)!

    【讨论】:

      【解决方案3】:

      yearshort,它是 Date 的直接成员。也就是说,如果您创建一个Stuff 对象,它包含birth,其中包含year。这些不需要手动分配,这是您尝试使用new short[sizeof(birth_year)] 执行的操作。相反,你应该给它一个值:

      actual->person->birth.year = 1990;
      

      您的错误的原因是new ... 表达式返回一个指向它们分配的对象的指针。这意味着它会给您一个short*,然后您尝试将其存储在short 中——这是行不通的。

      您遇到的另一个问题是new 不像malloc 那样工作。你只需传递你想要多少对象,而不是多少字节。如果你想要一个short,你只需做new short。如果你想要一个数组,比如说,两个shorts,你会做new short[2]。请记住,动态分配的对象必须是deleted - 对于动态分配的数组,您需要使用delete[] 来销毁它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-18
        • 1970-01-01
        • 1970-01-01
        • 2013-01-19
        • 2013-09-22
        • 2013-09-03
        相关资源
        最近更新 更多