[英]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.