0

我目前正在学习多重继承,并在创建一个继承其先前祖先变量和函数的函数时遇到了问题。问题出现在我进行多重继承的 showRoomServiceMeal() 函数中。当我编译时,我得到错误,指出相应的继承变量不能被继承,因为它们受到保护,并且继承的函数在没有对象的情况下使用。

我认为受保护的评估器允许其子级使用变量并访问相应的函数和受保护的变量,范围解析运算符 (::) 将被使用?谁能帮助解释为什么我会收到这些错误?

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

class RestaurantMeal
{
protected:
    string entree;
    int price;
public:
    RestaurantMeal(string , int );
    void showRestaurantMeal();
};

RestaurantMeal::RestaurantMeal(string meal, int pr)
{
    entree = meal;
    price = pr;
}

void RestaurantMeal::showRestaurantMeal()
{
    cout<<entree<<" $"<<price<<endl;
}

class HotelService
{
protected:
    string service;
    double serviceFee;
    int roomNumber;
public:
    HotelService(string, double, int);
    void showHotelService();
};

HotelService::HotelService(string serv, double fee, int rm) 
{
    service = serv;
    serviceFee = fee;
    roomNumber = rm;
}

void HotelService::showHotelService()
{
    cout<<service<<" service fee $"<<serviceFee<<
    " to room #"<<roomNumber<<endl;
}

class RoomServiceMeal : public RestaurantMeal, public HotelService
{
public:
    RoomServiceMeal(string , double , int );
    void showRoomServiceMeal();
};

RoomServiceMeal::RoomServiceMeal(string entree, double price, int roomNum) : 
RestaurantMeal(entree, price), HotelService("room service", 4.00, roomNum)
{
}

void showRoomServiceMeal()
{
    double total = RestaurantMeal::price + HotelService::serviceFee;
    RestaurantMeal::showRestaurantMeal();
    HotelService::showHotelService();
    cout<<"Total is $"<<total<<endl;
}


int main()
{
    RoomServiceMeal rs("steak dinner",199.99, 1202);
    cout<<"Room service ordering now:"<<endl;
    rs.showRoomServiceMeal();
    return 0;
}

使用 g++ 我得到这个错误:

RoomService.cpp: In function ‘void showRoomServiceMeal()’:
RoomService.cpp:18: error: ‘int RestaurantMeal::price’ is protected
RoomService.cpp:73: error: within this context
RoomService.cpp:18: error: invalid use of non-static data member ‘RestaurantMeal::price’
RoomService.cpp:73: error: from this location
RoomService.cpp:39: error: ‘double HotelService::serviceFee’ is protected
RoomService.cpp:73: error: within this context
RoomService.cpp:39: error: invalid use of non-static data member ‘HotelService::serviceFee’
RoomService.cpp:73: error: from this location
RoomService.cpp:74: error: cannot call member function ‘void RestaurantMeal::showRestaurantMeal()’ without object
RoomService.cpp:75: error: cannot call member function ‘void HotelService::showHotelService()’ without object
4

2 回答 2

1

您没有将函数定义showRoomServiceMeal为类的一部分RoomServiceMeal

void showRoomServiceMeal()
{
    ...
}

改成

void RoomServiceMeal::showRoomServiceMeal()
{
    ...
}

此外,在该showRoomServiceMeal方法中,您不必在访问父类成员时使用类前缀。而不是使用例如RestaurantMeal::price,您可以只使用price. 这是因为变量和函数在每个类中都是唯一的。

于 2012-08-23T06:35:07.240 回答
0

你忘记了 RoomServiceMeal:: 在 showRoomServiceMeal() 之前(让你的编译器认为这个函数是静态的而不是类相关的)

于 2012-08-23T06:34:03.863 回答