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

Odd C++ accessing private member issue

本文关键字:成员问题 访问 C++      更新时间:2023-10-16

我有一段代码:

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_iimplemented:

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不会出现同样的错误。我不明白为什么。

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

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

例如:

例外情况a;异常b=a;//错误:无法访问私人成员。。。