2014-06-29 162 views
-7

我收到了一个转换错误,实际上并不知道如何解决它。C++转换错误:从短int *无效转换为short int

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

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

错误消息:

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 
+0

错误信息在哪里? – Deduplicator

+4

这段代码没有意义。你为什么试图将一个数组分配给一个'short'? –

+0

[请详细阅读你的编译器告诉你的内容](http://ideone.com/poCJJk)!你的标题是错误的。你不需要'new()'在那里。 –

回答

3

您不能actual->person->birth.year分配内存,为birth.year不是指针。

你可以用:actual->person->birth.year = 2014;
actual->person->birth.year = birth_year;

2

我认为,你想要什么,真正做的是这样的:

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

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

你有你的结构:

short year;

但您试图将什么新回报分配给year

你应该这样做一个short* year;和动态处理它(永远不会忘记取消分配它)!

1

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

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

原因你的错误是new ...表达式返回一个指向他们所分配的对象。这意味着它给了你一个short*,然后你试图存储在short - 这是行不通的。

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