继承变量不可访问

Inheritance variables not accessible

本文关键字:访问 变量 继承      更新时间:2023-10-16

我想从继承的类中访问变量。但是,编译器给出错误:furniture.cpp:55:9:错误:"int stool::n_StoolLegs"在此上下文中是私有的one.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 

家具.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//

使用继承,private变量不可访问。使用 protected .