2010-11-24 2 views
6

Я преподаю C++ и начал создавать организатор списка для работы над концепцией указателей.C++ Object - Private int Возвращает странные значения

Я определил класс под названием List, который имеет три свойства:

int itemTotal; 
Item* firstItem; 
Item* lastItem; 

Конструктор устанавливает их значения, как:

itemTotal = 0; 
firstItem = NULL; 
lastItem = NULL; 

Я построил функцию, чтобы вернуть значение itemTotal :

int List::getItemTotal() 
{ 
    return itemTotal; 
} 

Сразу после создания объекта в моем драйвере, пунктОсновное начало ac (-858993460 каждый раз), несмотря на то, что в списке не было сделано никакой работы, и буквально ничего не произошло в программе. Я добавил кут к конструктору, чтобы увидеть, что там происходит, и он выдает значение 0, но как только этот конструктор будет выполнен, значение сразу изменится.

Я пытался разобраться с моими книгами и поиграть с ним, но я не могу решить проблему, поэтому решил, что обрадуюсь к кому-то, у кого больше опыта. Основное ниже:

int main() 
{ 
    List grocery; 
    cout << "itemTotal is now: " << grocery.getItemTotal() << endl; // Returns wrong value... 


    system("Pause"); 
    return 0; 
} 

С выходом выглядит как:

grocery List is built! 
itemTotal inside of the constructor is 0! 
itemTotal is now: -858993460 

Любые идеи? =/

EDIT: По желанию, весь класс (извините форматирование некрасиво, я не хочу, чтобы вновь сделать все это):

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; 

}

и конструктор:

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; 
} 
+2

Моя первая догадка неопределенное поведение где-то. Можете ли вы опубликовать код своего класса? – ereOn 2010-11-24 08:09:09

+1

Давайте посмотрим на ваш конструктор. – 2010-11-24 08:09:18

+2

Хм ... Очевидно, вы что-то скрываете от нас :) – 2010-11-24 08:09:23

ответ

7

Haaa! Вы инициализируете локальную переменную в конструкторе, а не в элементе! Вместо int itemTotal = 0; записи this->itemTotal = 0; или просто itemTotal = 0 или даже использовать список инициализации конструктора, как этот

List::list() 
    :itemTotal(0), 
    firstNode(NULL), 
    lastNode(NULL) 
{ 
    cout << "List ctor Called" 
} 
4

Вы указали локальные значения в своем конструкторе с тем же именем, что и члены. Они скрывают значение членов, поэтому, когда вы устанавливаете itemTotal = 0;, вы фактически устанавливаете значение локальной переменной. Ваш конструктор должен выглядеть так:

List::List() 
    :itemTotal(0), firstNode(NULL), lastNode(NULL) 
{ 
    cout << "item total should start at 0, it is " << itemTotal << " inside of the constructor." << endl; 

} 
2

Вы инициализации локальных переменных, а не члены класса.

Заменить:

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

By:

List::List() 
{ 
    firstNode = NULL; 
    lastNode = NULL; 
    itemTotal = 0; 
    cout << "item total should start at 0, it is " << nodeTotal << " inside of the constructor." << endl; 
} 
2

Ваша проблема заключается в том, что вы объявляете локальные переменные внутри конструктора, которые скрывают переменные-члены:

List::List() 
{ 
    Item* firstNode = NULL; // declares a new variable. 
    Item* lastNode = NULL; 
    int itemTotal = 0; 
    cout << "item total should start at 0, it is " << nodeTotal << " inside of the constructor." << endl; 
} 

Ваш код должен выглядят так:

List::List() 
{ 
    firstNode = NULL; 
    lastNode = NULL; 
    itemTotal = 0; 

    // fix this line: cout << "item total should start at 0, it is " << nodeTotal << " inside of the constructor." << endl; 
} 

Было бы еще лучше, если бы вы использовали список initializaer:

List::List() 
    : firstNode(NULL) 
    , lastNode(NULL) 
    , itemTotal(0) 
{ 
    // Fix this line cout << "item total should start at 0, it is " << nodeTotal << " inside of the constructor." << endl; 
} 
Смежные вопросы