奇怪的C ++访问私有成员问题

时间:2013-12-14 02:12:09

标签: c++

我有这段代码:

class object
{

public:
    virtual ~object(){ }

    bool equals(const object& J)const
    {
        return &J == this;
    }
    int operator==(const object& J)const
    {
        return equals(J);
    }
    virtual int getHash()const;
    virtual void getType()const;
    void* operator new(size_t size)
    {
        void*mem = malloc(size);
        return mem;
    }
};

class notcopyable
{
private:
    notcopyable(const notcopyable&){}
    notcopyable& operator=(const notcopyable&){}
public:
    notcopyable(){}
};

class exception :
    public object,public notcopyable
{
private:
public:
    virtual ~exception();
    virtual const char* info();
};

class exception_not_implemented :
    public exception
{
public:
    exception_not_implemented()
    {
    }
    virtual const char* info()
    {
        return "exception_not_implemented: ";
    }
};

class exception_oob :public exception
{
public:
    exception_oob()
    {

    }
    virtual const char* info()
    {
        return "Index out of boundary";
    }
};

有两个函数抛出exception_not_implemented:

void object::getType()const
{
    throw exception_not_implemented();
}

int object::getHash()const
{
    throw exception_not_implemented();
}

收到此错误:

error C2248: 'js::notcopyable::notcopyable' : cannot access private member declared in class 'js::notcopyable'  

编译器的输出说:

This diagnostic occurred in the compiler generated function 'js::exception::exception(const js::exception &)'

如果我删除上面显示的两个投掷,它运作良好。但是exception_oob不会发生同样的错误。我无法弄清楚原因。

2 个答案:

答案 0 :(得分:1)

您可以临时添加私有拷贝构造函数声明,这将在进行复制时生成错误。然后,您可以修复该代码以不进行复制。

答案 1 :(得分:0)

错误应该发生在您调用(私有)复制构造函数的其他位置。

例如:

例外a; 例外b = a; //错误:无法访问私有成员......