【问题标题】:How to access protected members in a multiple inherited class?如何访问多个继承类中的受保护成员?
【发布时间】:2017-09-26 04:27:28
【问题描述】:

我想在派生类的构造函数中使用受保护的成员,但我无法使用它。我有一堂课,我尝试将输出重定向到标准或其他流。这是我的代码。 重定向.h

#include <iostream>
#include <fstream>

class Redirection {
public:
    Redirection(std::ostream &stream)
    :outStream(stream)
    {
    };
    Redirection()
    :Redirection(std::cout)
    {
    };
protected:
    std::ostream &outStream;
};

派生的.h

#include "Redirection.h"

class Derived : public Base, public Redirection
{
public:
    Derived();
    Derived(std::ostream& stream);
    ~Derived();
};

派生的.cpp

#include "Derived.h"

Derived::Derived()
         :Derived(std::cout)  
{
}
Derived::Derived(std::ostream& stream)
         :Base(),
          oustream(stream)
{
}

当我尝试构建时,出现以下错误:

error: class 'Derived' does not have any field named 'outStream'

如果我这样修改:

    Derived::Derived(std::ostream& stream)
         :Base()              
{
     oustream = stream;
}

我收到以下错误:

error: 'std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator=(const std::basic_ostream<_CharT, _Traits>&) [with _CharT = char; _Traits = std::char_traits<char>]' is protected
   basic_ostream& operator=(const basic_ostream&) = delete;
error: within this context: mOutStream = stream;

我收到这些错误是因为多重继承?或者你知道如何解决它?

【问题讨论】:

  • 提示:哪一个基类的构造函数采用std::ostream&amp;
  • 重定向类。 Base 类只有虚方法
  • 好。那个构造函数允许你做什么?
  • 正如@juanchopanza 所暗示的,使用Redirection 类的构造函数将std::cout 转发到Derived 类的构造函数初始化列表中。
  • Derived::Derived(std::ostream&amp; stream) : Redirection(stream) 怎么样?这完美地初始化了outStream

标签: c++ inheritance protected


【解决方案1】:

作为评论中的状态,使用以下内容:

Derived::Derived(std::ostream& stream) : Base(), Redirection(stream) {}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-17
    • 2011-05-24
    • 2023-03-23
    • 2014-01-30
    • 2016-06-12
    • 2014-06-09
    • 2013-03-20
    • 1970-01-01
    相关资源
    最近更新 更多