C++ 过载标准::ostream&;操作员<&书信电报;在没有静态强制转换的派生类中<&燃气轮机;
这是重载C++ 过载标准::ostream&;操作员<&书信电报;在没有静态强制转换的派生类中<&燃气轮机;,c++,C++,这是重载ostream&operatorstatic_cast(b)的唯一方法吗 是安全的,没有任何错误,因为每个派生类对象也是基类对象,可以像基类对象一样处理 强制类型转换只有在不计后果地使用时才是危险的,您必须在需要的地方以正确的方式使用强制类型转换,这正是语言标准规定强制类型转换的目的。好吧。。。如果在结果定义不正确的情况下进行转换,则应避免转换,但转换到基础中始终是安全的 通过考虑派生引用衰减为基本引用,可以避免显式强制转换,因此可以使用隐式转换,如本例中所示: std::ostrea
ostream&operatorstatic_cast(b)的唯一方法吗
是安全的,没有任何错误,因为每个派生类对象也是基类对象,可以像基类对象一样处理
强制类型转换只有在不计后果地使用时才是危险的,您必须在需要的地方以正确的方式使用强制类型转换,这正是语言标准规定强制类型转换的目的。好吧。。。如果在结果定义不正确的情况下进行转换,则应避免转换,但转换到基础中始终是安全的
通过考虑派生引用衰减为基本引用,可以避免显式强制转换,因此可以使用隐式转换,如本例中所示:
std::ostream& operator<< (std::ostream& os, const Derived& b)
{
const Base& bs = b;
os << bs << " " << b.d_;
return os;
}
std::ostream&operator您可以像这样改变:
struct Base {
int b_;
void print(ostream &o) { o << b_; }
};
struct Derived : Base {
int d_;
void print(ostream &o) {
Base::print(o);
o << ' ' << d_;
}
};
ostream &operator<<(ostream &o, Base &b) {
b.print(o);
return o;
}
ostream &operator<<(ostream &o, Derived &d) {
d.print(o);
return o;
}
struct Base{
int b_;
void print(ostream&o){o如果您不喜欢强制转换,可以让操作员调用writeTo
函数,该函数使用模板方法模式实现
e、 g
}
这种模式也使人们需要使用操作符你的解决方案有什么问题?@K-ballo我想他想避免使用演员阵容。不过这没什么问题。@Seth Carnegie:为什么?演员阵容有什么问题?你怎么会调用操作符@K-ballo?你为什么问我?我刚才说没有问题。:)我问如果存在替代方案,那么xor首先是必要的…+1,因为你做了我认为提问者真正想要做的事情,以及避免强制转换的动机,只需要最小的代码更改。也就是说,你让编译器拒绝包含愚蠢错误的代码,比如切换Base
和Derived
,这样强制转换就是一个错误不安全的向下倾斜,而不是安全的向上倾斜。
std::ostream& operator<< (std::ostream& os, const Derived& b)
{
const Base& bs = b;
os << bs << " " << b.d_;
return os;
}
struct Base {
int b_;
void print(ostream &o) { o << b_; }
};
struct Derived : Base {
int d_;
void print(ostream &o) {
Base::print(o);
o << ' ' << d_;
}
};
ostream &operator<<(ostream &o, Base &b) {
b.print(o);
return o;
}
ostream &operator<<(ostream &o, Derived &d) {
d.print(o);
return o;
}
class Base {
public:
std::ostream& writeTo(std::ostream& ostr) const { os << b_; return this->doWriteTo(os); }
private:
int b_;
virtual std::ostream& doWriteTo(std::ostream& ostr) const = 0; // pure virtual
};
class Derived {
private:
int d_;
virtual std::ostream& doWriteTo(std::ostream& ostr) const {return ostr << d_;}
};
std::ostream& operator<<(std::ostream& ostr, const Derived& d) {
return d.writeTo(ostr);
std::ostream& operator<<(std::ostream& ostr, const Base& b) {
return b.writeTo(ostr);