继承变量不可访问

时间:2019-04-22 14:49:07

标签: c++ inheritance

我想从继承的类中访问变量。但是,编译器给出错误:furniture.cpp:55:9:错误:“ int凳:: n_StoolLegs”在此上下文中是私有的。n_StoolLegs -1;。

这是一项家庭作业,但该作业说我需要使用4个类型的凳子变量。因此,我继承了该类。可能还有另一种修改方式来修改继承的变量吗?

家具.hpp

#include <ostream>
#include <string>
#ifndef FURNIURE_HPP
#define FURNITURE_HPP

class stool{
private:
    int n_StoolLegs;
    int n_seats;

public:
    void setStoolLegs(int);
    int getStoolLegs();
    void setSeats(int);
    int getSeats();    
};

class table {};//not relevant

class furniture: public stool, public table
{
private:
    stool one;
    stool two;
    stool three;
    stool four;

    table first;

public:
    furniture(){
    one.setStoolLegs(4);
    one.setSeats(1);

    void makeMoreHipster();

};


#endif 

furniture.ccp:

#include <iostream>
#include "furniture.hpp"

//begin stool
void stool::setStoolLegs (int nLegs){
    n_StoolLegs = nLegs;
};

int stool::getStoolLegs(){
    return n_StoolLegs;
};


void stool::setSeats (int nSeats){
    n_seats = nSeats;
};

int stool::getSeats(){
    return n_seats;
};
//end stool//


// begin table

//not relevant

// end table

//start furniture

void furniture::makeMoreHipster(){
    one.n_StoolLegs -1;


};

// end furniture//

1 个答案:

答案 0 :(得分:-1)

通过继承,无法访问private变量。 使用protected