簡體   English   中英

運算符<<重載和常量引用

[英]Operator << Overload and Const References

我有一個帶有char *的類作為私有成員數據。 我將類的對象傳遞給<<的運算符重載。 如果我不使用const引用,則會收到一條錯誤消息,指出char *是私有成員數據。 如果我使用const引用,此錯誤就會消失。

通過const引用傳遞對象時,而不是通過引用傳遞對象時,私有成員數據是否可訪問?

碼:

// .h file
#include <iostream>
using namespace std;

class Flex
{  
    // The error was caused by having a const in the definition 
    // but not the declaration 
    // friend ostream& operator<<( ostream& o, const Flex& f );  

    // This fixed it
    friend ostream& operator<<( ostream& o, Flex& f );

    public:

    Flex();
    Flex( const char * );
    ~Flex();

    void cat( const Flex& f );

    private:

    char * ptr;
};

// .cpp file
#include <iostream>
#include <cstring>
#include "flex.h"
using namespace std;

Flex::Flex()
{
    ptr = new char[2];

    strcpy( ptr, " ");
}

Flex::Flex( const char * c )
{
    ptr = new char[strlen(c) + 1];

    strcpy( ptr, c );
}

Flex::~Flex()
{
    delete [] ptr;
}

void Flex::cat( const Flex& f )
{
    char * temp = ptr;

    ptr = new char[strlen(temp) + strlen(f.ptr) + 1];

    strcpy( ptr, temp );

    delete [] temp;

    strcat( ptr, f.ptr );
 }

ostream& operator<<( ostream& o, Flex& f )
{
    o << f.ptr;

    return 0;
}

// main.cpp
#include <iostream>
#include "flex.h"

using namespace std;

int main()
{

    Flex a, b("one"), c("two");

    b.cat(c);

    cout << a << b << c;

    return 0;

}

通過const引用傳遞對象時,而不是通過引用傳遞對象時,私有成員數據是否可訪問?

可見性和const性是正交的概念。 您可以通過const引用訪問private成員。

您不清楚所得到的實際錯誤是什么,還是真正的問題是什么。 但是,我猜您已經實現了一個免費的operator<<(ostream&, const MyClass&)函數,該函數以某種方式嘗試修改MyClass::ptr (或其他一些成員變量)。

如果是這樣,那將不起作用,因為引用是const 不要修改它的成員。

暫無
暫無

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

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