不同的值,試圖找到一個辦法讓我的動態轉換工作,但我不斷收到運行時錯誤。它在打印出來時跳轉到else語句塊的值(當它應該是一個if塊的值,但是當我在派生類中調用它時甚至沒有被使用,所以它顯示錯誤的值並且根本不會在。計算這是爲什麼感謝您的幫助使用動態投地返回變量中派生類
class Package
{
protected:
string name_and_address = "?";
double cost = 0.0;
double discount = 0.0;
double discount_rate = 0.0;
bool overnight_delivery = false;
bool insured = false;
string package_contents = "?";
double shipcost = 0.0;
public:
Package() {};
~Package() {};
protected:
virtual double calculate_cost() = 0;
class Video_Games {}; //defined the classes
class Genius_Phone {};
class Sausage {};
class Albums {};
// here I'm trying to change "shipcost" inside each of the derived classes
// to their respective and appropriate dollar values.
// However, I am getting a runtime error wherein it will jump DIRECTLY
// to the else statement 50.00 value for Video_Games
// and not even calculate the value as 50.00. SO it's doubly useless.
// It just skips to the else value and doesn't even factor
// that into the Video_Games calculation when I try to test it.
virtual double shipping_cost() {
if (dynamic_cast<Video_Games*>(this))
return 4.99;
else if (dynamic_cast<Genius_Phone*>(this))
return 25.00;
else if (dynamic_cast<Sausage*>(this))
return 9.00;
else
{
// should be assigned to class Albums,
// but is somehow being triggered by class Video_Games.
// Not sure why this is.
return 50.00;
}
}
};
class Video_Games :public Package
{
private:
int num_games = 0;
public:
Video_Games(string location, int number_of_games, bool express, bool insurance)
{
num_games = number_of_games;
name_and_address = location;
overnight_delivery = express;
insured = insurance;
package_contents = to_string(num_games) + " Video Game(s)";
cost = calculate_cost();
discount = calculate_discount();
shipcost = shipping_cost();
}
~Video_Games() {};
protected:
double calculate_cost()
{
cost = num_games * 19.99;
// this is where the magic should happen.
// shipcost here should be 4.99, but instead it's not even being used here.
// In fact - it's empty. I'm not sure why shipcost
// when set equal shipping_cost() is not returning that appropriate value.
// Very baffling.
if (overnight_delivery) { cost += shipcost; }
if (insured) { cost *= 1.06; }
return cost;
}
};
那是因爲你做錯了。你應該看看這個頁面如何使用它:http://en.cppreference.com/w/cpp/language/dynamic_cast – Asesh
你鏈接那個頁面很有趣。我試圖這樣做,我得到了同樣的最終結果。也許你可以告訴我如何以這種方式考慮這些代碼? – polymorphism
與問題無關 - 但爲什麼不使用某種多態的'GetShippingCost()'函數?這將是更可讀的方式,並會阻止你有這醜陋的條件/'dynamic_cast'混合。 – pSoLT