一个简单的成员函数使用成员变量的例子,出点小疑点
一个简单的成员函数使用成员变量的例子,出点小问题
代码如上,DevC里没错误,但没有输出。
VS里错误如下
补充:问题应该是由于head是没被初始化。
想知道为什么DevC里没有输出(即使是一个无意义的数)
------解决方案--------------------
struct Node{
int item;
Node *next;
//变量要初始化
Node():next(NULL),item(0)
{
}
};
------解决方案--------------------
VC在DEBUG模式会把你的局部变量初始化为0xCCCCCCCC,DEV不会
head没初始化就是随即值
因为是随即值 所以很有可能 if((head->next)==NULL) 条件并没有成立,所以不会执行到cout
- C/C++ code
#include<iostream> using namespace std; class Linked{ protected: struct Node{ int item; Node *next; }; Node* head; long length; public: Linked(){length=0;} void insert(int i){ if((head->next)==NULL){ Node* newItem; newItem->item=i; head->next=newItem; length++; cout<<this->length; } } }; int main() { Linked itr; itr.insert(2); system("pause"); return 0; }
代码如上,DevC里没错误,但没有输出。
VS里错误如下
- C/C++ code
Unhandled exception at 0x004114c8 in test.exe: 0xC0000005: Access violation reading location 0xccccccd0. First-chance exception at 0x004114c8 in test.exe: 0xC0000005: Access violation reading location 0xccccccd0.
补充:问题应该是由于head是没被初始化。
想知道为什么DevC里没有输出(即使是一个无意义的数)
------解决方案--------------------
struct Node{
int item;
Node *next;
//变量要初始化
Node():next(NULL),item(0)
{
}
};
------解决方案--------------------
VC在DEBUG模式会把你的局部变量初始化为0xCCCCCCCC,DEV不会
head没初始化就是随即值
因为是随即值 所以很有可能 if((head->next)==NULL) 条件并没有成立,所以不会执行到cout