我一直在教自己C++,并开始创建一个列表组织器来处理指针的概念.
我已经定义了一个名为List的类,它有三个属性:
int itemTotal;
Item* firstItem;
Item* lastItem;
Run Code Online (Sandbox Code Playgroud)
构造函数将其值设置为:
itemTotal = 0;
firstItem = NULL;
lastItem = NULL;
Run Code Online (Sandbox Code Playgroud)
我已经构建了一个函数来返回itemTotal的值:
int List::getItemTotal()
{
return itemTotal;
}
Run Code Online (Sandbox Code Playgroud)
在我的驱动程序中构建对象之后,itemTotal立即开始表现得很有趣并返回非常大的数字(每次都是-858993460),即使在List上没有完成任何工作,并且在程序中没有发生任何事情.我在构造函数中添加了一个cout,只是为了看看那里发生了什么,并且它回显了0值,但是一旦构造函数完成,值就会立即改变.
我一直试图用我的书来解决它并玩弄它,但我似乎无法解决这个问题,所以我想我会转向有经验的人.主要在以下:
int main()
{
List grocery;
cout << "itemTotal is now: " << grocery.getItemTotal() << endl; // Returns wrong value...
system("Pause");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出看起来像:
grocery List is built!
itemTotal inside of the constructor is 0!
itemTotal is now: -858993460
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?= /
编辑:每个请求,整个类(抱歉格式是丑陋的,我不想重新做这一切):
class List
{
public:
// Constructor
// Purpose: Builds object.
// Returns: Nothing.
// Pre-Conditions: None.
// Post-Conditions: Initializes null.
List();
// push_back function
// Purpose: Adds Item to end of List.
// Returns: None.
// Pre-Conditions: Must pass a declared Item object.
// Post-Conditions: None.
void push_back(Node*);
// push_front function
// Purpose: Adds Item to beginning of List.
// Returns: None.
// Pre-Conditions: Must pass a declared Item object.
// Post-Conditions: None.
void push_front(Node*);
// pop_back function
// Purpose: Removes last Item from List. Item is NOT deleted.
// Returns: Pointer to removed Item.
// Pre-Conditions: None.
// Post-Conditions: None.
Node* pop_back();
// pop_front function
// Purpose: Removes first Item from List. Item is NOT deleted.
// Returns: Pointer to removed Item.
// Pre-Conditions: None.
// Post-Conditions: None.
Node* pop_front();
// getFirst function
// Purpose: Returns pointer to first Item in List.
// Returns: Pointer.
// Pre-Conditions: List must have a Item object.
// Post-Conditions: None.
Node* getFirst();
// getItemTotal function
// Purpose: Returns the itemTotal
// Returns: Int
// Pre-Conditions: None.
// Post-Conditions: None.
int getItemTotal();
private:
Item* firstitem;
Item* lastitem;
int itemTotal;
Run Code Online (Sandbox Code Playgroud)
}
和构造函数:
List::List()
{
Item* firstNode = NULL;
Item* lastNode = NULL;
int itemTotal = 0;
cout << "item total should start at 0, it is " << nodeTotal << " inside of the constructor." << endl;
}
Run Code Online (Sandbox Code Playgroud)
HAAA!您正在构造函数中初始化局部变量而不是成员!而不是int itemTotal = 0;写this->itemTotal = 0;或只是itemTotal = 0甚至使用像这样的构造函数初始化列表
List::list()
:itemTotal(0),
firstNode(NULL),
lastNode(NULL)
{
cout << "List ctor Called"
}
Run Code Online (Sandbox Code Playgroud)