C ++抽象类操作符重载和接口执行问题 [英] C++ Abstract class operator overloading and interface enforcement question
问题描述
(从原始帖子编辑更改BaseMessage到const BaseMessage&)
Hello All,
我是C ++的新手,所以我希望你们的人可以帮助我看到我的方式的错误。
我有一个层次结构的消息,我试图使用抽象基类强制
一个接口。特别地,我想强制每个导出的消息提供重载的
<
当我尝试这样做时:
class BaseMessage
{
public:
//一些非纯虚函数声明
//一些纯虚函数声明
虚拟ostream& operator<<(ostream& stream,const BaseMessage& objectArg)= 0;
}
编译器会提示
错误:无法将参数objectArg声明为抽象类型BaseMessage
我相信还有朋友 ,但是当我试图将其声明为:
virtual friend ostream& operator<<<(ostream& stream,const BaseMessage objectArg)= 0 ;
编译器添加了一个附加错误
错误:虚函数不能是否有一种方法可以确保我的所有派生(消息)类提供一个<ostream操作符?
感谢很多,
Steve
这个常见的惯例是在基本级别有一个 friend
输出运算符,并且调用private virtual function:
class Base
{
public:
///不要忘记这个
virtual〜Base ();
/// std stream interface
friend std :: ostream&operator<<(std :: ostream&out,const Base&b)
{
b.Print (out);
return out;
}
private:
///派生接口
virtual void Print(std :: ostream&)const = 0;
};
(edited from original post to change "BaseMessage" to "const BaseMessage&")
Hello All, I'm very new to C++, so I hope you folks can help me "see the errors of my ways".
I have a hierarchy of messages, and I'm trying to use an abstract base class to enforce an interface. In particular, I want to force each derived message to provide an overloaded << operator.
When I try doing this with something like this:
class BaseMessage
{
public:
// some non-pure virtual function declarations
// some pure virtual function declarations
virtual ostream& operator<<(ostream& stream, const BaseMessage& objectArg) = 0;
}
the compiler complains that
"error: cannot declare parameter ‘objectArg’ to be of abstract type ‘BaseMessage’
I believe there are also "friend" issues involved here, but when I tried to declare it as:
virtual friend ostream& operator<<(ostream& stream, const BaseMessage objectArg) = 0;
the compiler added an addition error
"error: virtual functions cannot be friends"
Is there a way to ensure that all of my derived (message) classes provide an "<<" ostream operator?
Thanks Much,
Steve
The common convention for this is to have a friend
output operator at the base level and have it call private virtual function:
class Base
{
public:
/// don't forget this
virtual ~Base();
/// std stream interface
friend std::ostream& operator<<( std::ostream& out, const Base& b )
{
b.Print( out );
return out;
}
private:
/// derivation interface
virtual void Print( std::ostream& ) const =0;
};
这篇关于C ++抽象类操作符重载和接口执行问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!