如何访问多重继承 class 中的受保护成员?
How to access protected members in a multiple inherited class?
我想在派生 class 的构造函数中使用受保护的成员,但我无法使用它。我有一个 class 尝试将输出重定向到标准或其他流。这是我的代码。
Redirection.h
#include <iostream>
#include <fstream>
class Redirection {
public:
Redirection(std::ostream &stream)
:outStream(stream)
{
};
Redirection()
:Redirection(std::cout)
{
};
protected:
std::ostream &outStream;
};
Derived.h
#include "Redirection.h"
class Derived : public Base, public Redirection
{
public:
Derived();
Derived(std::ostream& stream);
~Derived();
};
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;
我收到这些错误是因为多重继承?或者您知道如何解决它吗?
如评论中所述,使用以下内容:
Derived::Derived(std::ostream& stream) : Base(), Redirection(stream) {}
我想在派生 class 的构造函数中使用受保护的成员,但我无法使用它。我有一个 class 尝试将输出重定向到标准或其他流。这是我的代码。 Redirection.h
#include <iostream>
#include <fstream>
class Redirection {
public:
Redirection(std::ostream &stream)
:outStream(stream)
{
};
Redirection()
:Redirection(std::cout)
{
};
protected:
std::ostream &outStream;
};
Derived.h
#include "Redirection.h"
class Derived : public Base, public Redirection
{
public:
Derived();
Derived(std::ostream& stream);
~Derived();
};
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;
我收到这些错误是因为多重继承?或者您知道如何解决它吗?
如评论中所述,使用以下内容:
Derived::Derived(std::ostream& stream) : Base(), Redirection(stream) {}