我不知道你是如何試圖訪問變量,但一個簡單的公共職能將打印正確的值:
class Video_Games :public Package
{
private:
int num_games = 0;
double shipcost = 4.99;
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();
}
~Video_Games() {};
void PrintVars(ostream& out)
{
out << num_games << '\t' << shipcost << '\n';
}
protected:
double calculate_cost()
{
cost = num_games * 19.99;
if (overnight_delivery) {
cost += shipcost;
}
if (insured) {
cost *= 1.06;
}
return cost;
}
};
Video_Games vg("abcde",10,true,true);
vg.PrintVars(cout);
我仍然不知道如果我得到了它。在我看來,設置shipcost的值,而不是宣佈一個新的,可以讓每一個派生類來訪問自己的價值:
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;
void PrintVars(ostream& out)
{
cout << "Cost = " << cost << '\n'
<< "Discount = " << discount << '\n'
<< "Discount Rate = " << discount_rate << '\n'
<< "Ship Cost = " << shipcost << '\n';
}
};
class Video_Games :public Package
{
private:
int num_games = 0;
public:
Video_Games(string location , int number_of_games , bool express , bool insurance)
{
shipcost = 4.99;
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();
}
~Video_Games() {};
void Print(ostream& out)
{
PrintVars(out);
}
protected:
double calculate_cost()
{
cost = num_games * 19.99;
if (overnight_delivery) {
cost += shipcost;
}
if (insured) {
cost *= 1.06;
}
return cost;
}
};
class Board_Games :public Package
{
private:
int num_games = 0;
public:
Board_Games(string location , int number_of_games , bool express , bool insurance)
{
shipcost = 3.99;
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();
}
~Board_Games() {};
void Print(ostream& out)
{
PrintVars(out);
}
protected:
double calculate_cost()
{
cost = num_games * 19.99;
if (overnight_delivery) {
cost += shipcost;
}
if (insured) {
cost *= 1.06;
}
return cost;
}
};
Video_Games vg("abcde",10,true,true);
vg.Print(cout);
cout << '\n';
Board_Games bg("cdefg" , 20 , false , false);
bg.Print(cout);
這會產生這樣的回報:
Cost = 217.183
Discount = 0
Discount Rate = 0
Ship Cost = 4.99
Cost = 399.8
Discount = 0
Discount Rate = 0
Ship Cost = 3.99
*「所以它正在被正確使用......」 - - 實際上,事實並非如此。你不能像C++那樣「覆蓋」成員變量的值。可以使用參數在構造函數中初始化成員變量,也可以創建一個虛擬成員函數來返回運輸成本。 –
看起來你在基類和派生類中都有「shipcost」。這會讓你度過一個糟糕的一天。 – DiB
lol @ DiB ...謝謝你澄清。我有一個預感,船舶不會返回任何事情都會成爲頭痛。 – polymorphism