You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多继承场景下访问父类私有变量的技术求助

Fixing Private Member Access in C++ Multiple Inheritance

Hey there! Let's work through this private member access issue you're hitting with your stteacher multi-inherited class. The root of the problem is straightforward: even though stteacher inherits from both student and teacher, their private members (str and salary) are restricted to access only within their own class definitions—subclasses (even multi-inherited ones) can't directly reach them.

Luckily, there are two clean solutions that fit your requirements (no new variables, no making members public):

Option 1: Switch to Protected Access Modifiers

The simplest fix is to change the access level of str and salary from private to protected. Protected members are only accessible to the class itself and its derived classes (including multi-inherited ones like stteacher), keeping them hidden from external code just like private members.

Modify your student and teacher classes like this:

class student : public virtual person {
    friend class ststudent;
protected: // Changed from private
    long str;
public:
    student(char*n, char*ln, long s);
    void print(ostream&o);
};

class teacher : public virtual person {
protected: // Changed from private
    long salary;
public:
    teacher(char*n, char*ln, long s);
    virtual void print(ostream&o);
};

Now your stteacher::print function will work exactly as you wrote it, since it can access the protected members directly.

Option 2: Add Protected Getter Methods

If you want to keep str and salary strictly private (to enforce stronger encapsulation), you can add protected getter methods to student and teacher. These methods give derived classes a controlled way to access the private values without exposing them publicly.

Update student to include a getter:

class student : public virtual person {
    friend class ststudent;
    long str;
public:
    student(char*n, char*ln, long s);
    void print(ostream&o);
protected:
    long getStudentID() const { return str; } // Protected getter
};

Do the same for teacher:

class teacher : public virtual person {
    long salary;
public:
    teacher(char*n, char*ln, long s);
    virtual void print(ostream&o);
protected:
    long getSalary() const { return salary; } // Protected getter
};

Then adjust your stteacher::print function to use these getters:

void stteacher::print(ostream& o) {
    person::print(o);
    o << "st_num : " << getStudentID() << "\nsalary : " << getSalary() << endl;
}

Either approach will solve your problem while respecting your constraints. Option 1 is quicker, while Option 2 maintains stricter encapsulation of the original private members.

内容的提问来源于stack exchange,提问作者Meis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:39:15