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;
}
隨着最小的改動,[編譯正常](http://coliru.stacked-crooked.com/a/0ddddb3380eeb496)。請製作[SSCCE](http://sscce.org)。 – chris
「我有一個char *作爲私有成員數據的類。」 ** Gross。**使用'std :: string' –
爲什麼不發佈你的**真實代碼**?給定的代碼只是讓我們猜測。也許你在真實代碼中有不同的錯字? –