【发布时间】:2013-12-13 17:04:28
【问题描述】:
我有一个带有 char * 作为私有成员数据的类。我将类的一个对象传递给
当对象通过 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;
}
【问题讨论】:
-
改动很小,compiles fine。请提供SSCCE。
-
"我有一个带有 char * 作为私有成员数据的类。" 毛。使用
std::string -
为什么不发布您的真实代码?给定的代码只是让我们猜测。也许你的真实代码中有不同的拼写错误?
-
@Caulibrot:它可以编译,但会写入它不拥有的内存(
new char [0]返回一个有效的指针,但你不能取消引用它)。你的cat也坏了,在删除它后尝试使用它的缓冲区。 -
您的代码依赖于 NUL 终止的缓冲区,因此您可能需要
ptr[0] = '\0';。cat现在会泄漏内存。哦,既然你还没有初始化从new返回的缓冲区,你真的想要strcpy(ptr, temp);而不是strcat。然后在后面加上delete [] temp;,以消除内存泄漏。
标签: c++ reference operators constants