继承受保护函数和公共变量C ++的多继承编译错误

时间:2012-08-23 06:22:09

标签: c++ inheritance protected

我目前正在学习多重继承,并遇到一个问题,即创建一个继承其先前祖先变量和函数的函数。问题发生在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

2 个答案:

答案 0 :(得分:1)

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

void showRoomServiceMeal()
{
    ...
}

更改为

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

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

答案 1 :(得分:0)

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