错误:无效的分配大小 [英] Error: Invalid Allocation Size

查看:198
本文介绍了错误:无效的分配大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Stack
{
    int *ptrStack;
    int top;
    int size;

public:
    Stack(int = 10);                    // Default Constructor
};

Stack::Stack(int s): size(s > 0 ? s ? : 10), top(-1), ptrStack (new int[size])
{
     // Body
}

main()
{
     Stack<integer> intStack(7);
}


运行上述示例时,出现调试错误:无效的分配大小.通过调试示例,我知道" size "未初始化,并获得了一些垃圾值.
请更正我犯的错误.

谢谢
Abid


As I Run the above sample, I get the Debug Error: Invalid Allocation Size. By debugging the sample, I came to know that "size" is not initializes and take some garbage value.
please correct the mistake, I made.

Thanks
Abid

推荐答案

Aabid写道:

size(s> 0?s? :10)

size(s > 0 ? s ? : 10)


上面应该是:


The above should be:

size(s > 0 ? s : 10)


成员变量的初始化顺序是在类定义中定义的,而不是它们在构造函数的初始化列表中出现的顺序. http://codewrangler.home.comcast.net/~codewrangler/tech_info/ctor_init.html# InitializationOrder [ ^ ]
http://www.goingware.com/tips/parameters/membervars.html [ ^ ]
这导致ptrStack首先被初始化,而size仍未定义.将您的类定义重新排列为:
The member variables are initialized in the order they are defined in the class definition, not in the order they appear in the constructor''s initialization list. http://codewrangler.home.comcast.net/~codewrangler/tech_info/ctor_init.html#InitializationOrder[^]
http://www.goingware.com/tips/parameters/membervars.html[^]
This causes ptrStack to be initialized first, while size is still undefined. Rearrange your class definition to:
class Stack
{
    int size;
    int top;
    int *ptrStack;
public:
    Stack(int = 10);                    // Default Constructor
};


这篇关于错误:无效的分配大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆