2013-12-13 45 views
0

我有一個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; 

} 
+1

隨着最小的改動,[編譯正常](http://coliru.stacked-crooked.com/a/0ddddb3380eeb496)。請製作[SSCCE](http://sscce.org)。 – chris

+0

「我有一個char *作爲私有成員數據的類。」 ** Gross。**使用'std :: string' –

+1

爲什麼不發佈你的**真實代碼**?給定的代碼只是讓我們猜測。也許你在真實代碼中有不同的錯字? –

回答

1

Is private member data accessible when an object is passed by const reference and not when it is passed by reference?

可視性和const岬是正交的概念。您可以通過const參考訪問private成員。

你很不清楚你得到的實際錯誤是什麼,或者真正的問題是什麼。不過,我猜你已經實現了一個免費的operator<<(ostream&, const MyClass&)函數,它試圖修改MyClass::ptr(或其他成員變量)。

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