- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
所以我有 A 类和 B 类,其中 B 类扩展了 A 类。我必须在这两个类中重载 << 和 >>。我希望在类 B 的运算符的函数定义中,我可以调用类 A 的重载运算符,但我在这样做时遇到了麻烦。
#include <iostream>
#include <string>
using namespace std;
class A {
friend ostream& operator<<(ostream& out, A a);
protected:
int i;
string st;
public:
A(){
i=50;
st = "boop1";
}
};
ostream& operator<<(ostream &out, A a) {
out << a.i << a.st;
return out;
}
class B : public A {
friend ostream& operator<<(ostream& out, B b);
private:
int r;
public:
B() : A() {
r=12;
}
};
ostream& operator<<(ostream &out, B b) {
out = A::operator<<(out, b); //operator<< is not a member of A
out << "boop2" << b.r;
return out;
}
int main () {
B b;
cout << b;
}
我试图在B版本的operator<<中调用A版本的operator<<,当然它实际上并不属于A,因此无法编译。我应该如何实现这一目标?
另外请注意,实际上 A 和 B 有自己的头文件和正文文件。
最佳答案
你可以让你的B
对象看起来像一个A
对象:
std::ostream& operator<< (std::ostream& out, B const& b) {
out << static_cast<A const&>(b);
out << "boop2" << b.r;
return out;
}
请注意,您几乎肯定不想按值传递要打印的对象。我已将签名更改为使用 const&
:这表明该对象不会被更改,也不会被复制。
关于c++ - 在 C++ 中继承友元运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12522624/
在 C++ 中,我使用多态类和友元来创建一个基本的“ friend 组”。但是,当我尝试访问类人(男孩类的 friend )的私有(private)年龄函数时,我无法访问它。有什么问题吗? /* Po
当一个 lambda 函数在 C 类的友元函数 F 中声明时,该 lambda 函数是否可以访问 C私有(private)成员(member)?具体来说,标准允许吗? 最佳答案 C++11 §[exp
首先回顾以前所学的构造函数 类的构造函数用于对象的初始化 构造函数与类同名并且没有返回值 构造函数在定义时被自动调用 由于构造函数没有返回值不能判断执行结果,所以不能保证初始
我想要一个模板化的友元函数。但是,我不知道如何使它在没有模板化功能的情况下以相同的方式工作。这是一个示例代码 #include namespace ns{ struct Obj { frie
我目前正在创建一个实用程序类,其中将包含重载的运算符。使它们成为成员或非成员 (friend) 函数的优缺点是什么?还是根本不重要?也许对此有最佳实践? 最佳答案 我会选择“C++ 编码标准:101
template struct test { template friend struct test; }; int main() {} 这是完全有效的代码,不是吗?我问是因为 MSVC+
相对于Java而言,友元是C++中特有的一种元素,很多教材上对其介绍的相对较少,因此初学的时候往往不能很快掌握,本文总结了友元的用法和一些注意的地方,供大家参考借鉴。希望能对初学C++的朋友起到一点
类中声明的友元函数和公共(public)函数有什么区别?当我们可以将好友功能公开并具有相同的访问权限时,使用好友功能还有什么意义呢? 最佳答案 public 指类成员函数的访问级别。 成员函数可以是公
如何在所有派生类中没有 friend 的情况下访问 privateMember? class parent{...}; //a virtual class class A: public paren
我是初学者级别的面向对象编程爱好者。我遇到了以下难题: class A { }; class B { protected: friend class A; }; class C { publi
前言:这些知识点属于C++较为前期的内容,博主在今年刷笔试题的时候遇到多次,所以特地这这篇博客再复习了一下。 1.构造函数的初始化 在推导之前,关于初始化我们先达成一点共识:初始化只能一次(记住这点)
大家好, 我正在尝试为我的数学 vector 类重载加法运算符。我的(看似逻辑正确的)简化代码是: template class Vector2 { private: T m_da
我是一名优秀的程序员,十分优秀!