C++ 如何呼叫接线员>&燃气轮机;在派生类中?
如何从派生类调用基类的运算符>>?在派生类中我想读A和B,但我不知道如何正确地做,非常感谢C++ 如何呼叫接线员>&燃气轮机;在派生类中?,c++,C++,如何从派生类调用基类的运算符>>?在派生类中我想读A和B,但我不知道如何正确地做,非常感谢 class Base { public: friend istream& operator>>(istream& input, Base &base) { input >> A; } protected: int A; }; class Derived: public Base { public: frien
class Base {
public:
friend istream& operator>>(istream& input, Base &base) {
input >> A;
}
protected:
int A;
};
class Derived: public Base {
public:
friend istream& operator>>(istream& input, Derived &derived) {
// How can I call the operator >> from base class?
input >> B;
}
protected:
int B;
}
首先,由于
操作符>>
是友元函数而不是成员函数,因此需要更改base的实现:
class Base {
public:
friend istream& operator>>(istream& input, Base &base) {
input >> base.A;
}
private:
int A;
};
对于衍生的:
class Derived: public Base {
public:
friend istream& operator>>(istream& input, Derived &derived) {
input >> static_cast<Base&>(derived);
input >> derived.B;
}
private:
int B;
};
对于用户(一个获取基本引用的函数)来说,很难知道如何使用这样的对象
同时阅读如果您想在多态情况下使用它,您可能需要如下定义某种类型的读取虚拟函数:
class Base {
public:
virtual istream& read(istream& in) {
return in >> A;
}
// private: // for demo
int A = 0;
};
class Derived: public Base {
public:
virtual istream& read(istream& in) {
Base::read(in);
return in >> B;
}
//private: // for demo
int B = 0;
};
istream& operator>>(istream& input, Base &base) {
return base.read(input);
}
请注意,在这段代码中,操作员>
不是任何人的朋友
使用输入12
,以下程序按预期工作
int main() {
Derived d;
Base& b = d;
cout << d.B << " - " << d.A << endl; // 0 - 0
cin >> b;
cout << d.B << " - " << d.A << endl; // 1 - 2
return 0;
}
intmain(){
导出d;
基数&b=d;
CUT必须是使用派生类重写的虚拟函数,并且有一个用于调用内部函数的基类的单个提取器,这是简单的。这样,就不必有每个类的朋友。C++也不支持开放式多方法。在多态的情况下,它不会像人们所期望的那样工作。与问题相关,但您缺少一些返回语句。它仍在中断。只有知道参考b是什么,您才能知道它将吃掉多少流,这可能是非常出乎意料的。@JohanLundberg您谈论的是哪种特定LSP?在这种情况下,您可以说这是目的,但我考虑的是post条件:让一个派生类从一个流中吃掉不同数量的(并以不同的方式使用)是可疑的。这也是文章中提到的“如果s是T的子类型,那么程序中T类型的对象可以替换为s类型的对象,而不改变该程序的任何期望属性(例如,正确性)。”程序的理想属性或正确性只取决于程序员的定义。好吧,这样的原则可以帮助你知道什么时候你会陷入困境。你总是可以说服自己它们不适用于你的情况。你认为这是好代码吗?
class Base {
public:
virtual istream& read(istream& in) {
return in >> A;
}
// private: // for demo
int A = 0;
};
class Derived: public Base {
public:
virtual istream& read(istream& in) {
Base::read(in);
return in >> B;
}
//private: // for demo
int B = 0;
};
istream& operator>>(istream& input, Base &base) {
return base.read(input);
}
int main() {
Derived d;
Base& b = d;
cout << d.B << " - " << d.A << endl; // 0 - 0
cin >> b;
cout << d.B << " - " << d.A << endl; // 1 - 2
return 0;
}