【问题标题】:Operator << Overload and Const References运算符 << 重载和常量引用
【发布时间】: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


【解决方案1】:

当对象通过 const 传递时是否可以访问私有成员数据 引用而不是引用传递的时候?

可见性和constness 是正交概念。您可以通过const 引用访问private 成员。

您很不清楚您遇到的实际错误是什么,或者真正的问题是什么。不过,我猜你已经实现了一个免费的operator&lt;&lt;(ostream&amp;, const MyClass&amp;) 函数,它试图以某种方式修改MyClass::ptr(或其他一些成员变量)。

如果是这样,那将不起作用,因为引用是 const。不要修改它的成员。

【讨论】:

    猜你喜欢
    • 2013-10-14
    • 2012-05-04
    • 2010-10-19
    • 1970-01-01
    • 2013-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多