2013-07-29 5 views
-3

Я думаю, что я был в состоянии исправить свой код, чтобы он компилировался, но что-то по-прежнему не работает.Компиляция кода Странно

Это мой .h файл

#pragma once 
#include <string> 
using namespace std; 

class Item 
{ 
private: 
string description; 
double price; 
int weight; 
int quantity; 

public: 
Item(void); 
~Item(void); 
Item::Item(double OrderPrice, int OrderWeight, string Description); 
void setOrderPrice(double amount); 
void setOrderWeight(int ounces); 
void setDescription(string desc); 
void setQuantity(int number); 

int getOrderPrice(); 
int getOrderWeight(); 
string getDescription(); 
int getQuantity(); 

void show(); 
}; 

Это мой .cpp файл:

#include <iostream> 
#include <string> 
#include "Item.h" 
using namespace std; 

Item::Item(void) 
{ 
} 

Item::Item(double OrderPrice, int OrderWeight, string Description) 
{ 
} 

Item::~Item(void) 
{ 
} 

void Item::setOrderPrice(double amount) { 
price = amount; 
} 

void Item::setOrderWeight(int ounces) { 
weight = ounces; 
} 

void Item::setDescription(string desc) { 
description = desc; 
} 

void Item::setQuantity(int number) { 
quantity = number; 
} 

int Item::getOrderPrice() { 
return price; 
} 

int Item::getOrderWeight() { 
return weight; 
} 

string Item::getDescription() { 
return description; 
} 

int Item::getQuantity() { 
return quantity; 
} 

void Item::show() { 
cout << price << weight << description; 
} 

Это мой главный файл:

#include <iostream> 
#include <string> 
#include "Item.h" 
using namespace std; 

int main() { 
double dTotalPrice = 0.0; 
int iTotalWeight = 0; 
Item itmMouse(24.99, 14, "Wireless Mouse"); 
Item itmKeyboard(22.49, 27, "USB Keyboard"); 
Item itmHDMI (24.99, 12, "HDMI Cable"); 
Item itmGlasses(7.99, 7, "Reading Glasses"); 
itmGlasses.setQuantity(2); 
// Show the details of the order using printDetails() 
cout << "Here are your shopping cart contents.\n"; 
itmMouse.show(); 
itmKeyboard.show(); 
itmHDMI.show(); 
itmGlasses.show(); 
// Compute the total price and total weight in this section 
dTotalPrice += itmMouse.getOrderPrice(); 
dTotalPrice += itmKeyboard.getOrderPrice(); 
dTotalPrice += itmHDMI.getOrderPrice(); 
dTotalPrice += itmGlasses.getOrderWeight(); 
iTotalWeight += itmGlasses.getOrderPrice(); 
iTotalWeight += itmKeyboard.getOrderWeight(); 
iTotalWeight += itmHDMI.getOrderWeight(); 
iTotalWeight += itmGlasses.getOrderWeight(); 
// Here we show the order details 
cout << "The price of your order is $ " << dTotalPrice << endl; 
cout << "The shipping weight is " << iTotalWeight << " ounces\n"; 
cout << "That is " << iTotalWeight/16 << " pounds\n"; 

return 0; 

} 

Я интересно знать, где Я ошибся.

Заранее благодарен!

+0

Так что же такое «прочь»? – Daniel

+10

Вы явно поступили не так, когда не указали, какое сообщение об ошибке вы получите ... – ppeterka

+0

Он компилируется со странными числами вместо значений, похожих на то, что я должен получать. – David

ответ

4

В вашем файле .h:

Item::Item(double OrderPrice, int OrderWeight, string Description); 

Должно быть:

Item(double OrderPrice, int OrderWeight, string Description); 

Нет необходимости квалифицировать второй конструктор.

Также обратите внимание:

int Item::getOrderPrice() { 
    return price; 
} 

Цена является double и вы возвращаете int. И, наконец:

iTotalWeight += itmGlasses.getOrderPrice(); 

Вы добавляете «Цена» в свой «Вес» - возможно, не то, что вы хотели.

Последнее, что вы не сохраняете свои значения из своего конструктора item() в любом из ваших варов. использовать список инициализации в конструкторе item.cpp файла:

Item::Item(double OrderPrice, int OrderWeight, string Description): 
    description(Description), 
    price(OrderPrice), 
    weight(OrderWeight), 
    quantity(1) 
... 

компилятора предупреждения/ошибки помечаются все эти вопросы для меня ...

0

Ok, ваш конструктор не инициализирует член класса

Item::Item() : description(""), price(0), weight(0), quantity(0) 
    {} 

    item::Item(double OrderPrice, int OrderWeight, string Description) : 
    description(Description), 
    price(OrderPrice), 
    .... etc.... 
    {} 

Таким образом, ваш призыв к «получателю» возвращает неинициализированные значения.

2

Вы забыли рассказать нам, что пошло не так. Может быть, вы получите ошибку компиляции, так как (в определении класса) в объявлении конструктора

Item::Item(double OrderPrice, int OrderWeight, string Description); 

должен быть просто

Item(double OrderPrice, int OrderWeight, string Description); 

Или, возможно, он собирает для вас (так как некоторые компиляторы принимают эту ошибку), но вы получаете странные результаты. Это связано с тем, что этот конструктор не инициализирует члены, поэтому они имеют значения мусора. Может быть, вы хотите:

Item::Item(double OrderPrice, int OrderWeight, string Description) : 
    description(Description), 
    price(OrderPrice), 
    weight(OrderWeight), 
    quantity(1) 
{} 

Он также может быть хорошей идеей, чтобы удалить конструктор по умолчанию, так что пользователи не могут случайно создать неиницализированные объект.

0

Чтобы получить хорошие результаты при переполнении стека, и чтобы помочь вам научиться, ключевым шагом является создание небольших воспроизводимых тестовых примеров, в которых четко указано, что вы ожидаете, и что вы получаете.

Сведем код:

#include <iostream> 
#include <string> 
#include <cassert> 
using namespace std; 

class Item 
{ 
    private: 
     string description; 
     double price; 
     int weight; 
     int quantity; 

    public: 
     Item(double OrderPrice, int OrderWeight, string Description); 
     int getOrderPrice(); 
}; 

Item::Item(double OrderPrice, int OrderWeight, string Description) 
{ 
} 

int Item::getOrderPrice() { 
    return price; 
} 

int main() { 
    Item itmMouse(24.99, 14, "Wireless Mouse"); 
    assert(itmMouse.getOrderPrice() == 24.99); 
} 

Теперь, для тех, кто смотрит на этот код, (и вы должны включить примечание об этом, а), то становится ясно, что путаница в том, что ваша цена является неправильным. И на этом этапе мы можем четко сказать, что проблема заключается в том, что ваш конструктор не копирует свои аргументы членам класса.

Потенциальный фикс будет конструктор, который выглядит следующим образом:

Item::Item(double OrderPrice, int OrderWeight, string Description) 
{ 
    price = OrderPrice; 
    weight = OrderWeight; 
    description = Description; 
    quantity = 1; 
} 

Вместо этого утверждают, что я использую, мы могли бы также просто посмотреть на выходе Item::show(). Эта строка является первым пунктом в вашем исходном коде, где что-то выходит, что вы не ожидаете. Вот где я начал, когда я сократил ваш код.

Смежные вопросы