簡體   English   中英

在訪問私有元素時重載 << 運算符(朋友)

[英]overloading << operator whilst accessing private elements (friend)

我正在編寫一個程序,要求我在訪問 class 的private成員時重載<<運算符。 它是這樣的:

#pragma once
#include <ostream>
#include "B.h"

using namespace std;

class A {
public:

    A(B* b) {
        this->b = b;
        this->x = 0;
    }

    friend ostream& operator<<(ostream& os, A& a)
    {
        os << "this is a " << a.x;
        return os;
    }

private:
    int x;
    B* b;
};

溴化氫

#pragma once
#include <ostream>

using namespace std;

class B {
public:

    B(int x) {
        this->x = x;
    }
    
    friend ostream& operator<<(ostream& os, B& b)
    {
        os << "this is B " << b.x;
        return os; 
    }

private:
    int x;
};

主文件

#include <iostream>
#include "A.h"
#include "B.h"

using namespace std;

int main()
{
    B* b = new B(1);
    A* a = new A(b);
    cout << a << endl;
    cout << b << endl;
}

但是,這不會打印ab ,只是打印兩個對象的 memory 地址。 我認為這與操作順序有關,但我不確定。

另外,我不能將ostream& operator<<()用作獨立的 function,因為這會阻止我訪問 class 的私有成員。 我可能會在 class 中實現一個void print()並使用它來打印私有成員,但我認為這不是我的教授的想法(考慮到已經為其他東西實現了一個void print() )。

main()中, ab是指針。 這段代碼:

cout << a
cout << b

有效地調用這個:

cout.operator<<(a)
cout.operator<<(b)

因為std::ostream有一個成員operator<<(void*)用於打印指針,並且所有指針都可以隱式轉換為void* 這就是您在 output 中看到 memory 地址的原因。 根本不會調用您的自定義運算符,因為它們要求您將實際的 object 實例傳遞給operator<< ,而您沒有這樣做。

您需要取消引用main()中的指針,例如:

#include <iostream>
#include "A.h"
#include "B.h"

using namespace std;

int main()
{
    B* b = new B(1);
    A* a = new A(b);
    cout << *a << endl;
    cout << *b << endl;
    delete a;
    delete b;
}

在這段代碼中:

cout << *a
cout << *b

由於std::ostream沒有AB的成員operator<< s,這將有效地調用它:

operator<<(cout, *a)
operator<<(cout, *b)

這將調用您的自定義運算符。

否則,只需完全擺脫指針:

#include <iostream>
#include "A.h"
#include "B.h"

using namespace std;

int main()
{
    B b(1);
    A a(&b);
    cout << a << endl;
    cout << b << endl;
}

這也將有效地稱為:

operator<<(cout, a)
operator<<(cout, b)

從而調用您的自定義運算符。


附帶說明一下,您的自定義運算符應該接受對const A + B對象的引用,例如:

friend ostream& operator<<(ostream& os, const A& a)
friend ostream& operator<<(ostream& os, const B& b)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM