c++ - 奇怪的 C++ 访问私有(private)成员问题

标签 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";
    }
};

有两个函数throw 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 &)'

如果我删除上面显示的两个 throw,效果很好。但是exception_oob不会发生同样的错误。我不明白为什么。

最佳答案

可以临时添加一个私有(private)的拷贝构造函数声明,在拷贝的时候会报错。然后您可以修复该代码以使其不进行复制。

关于c++ - 奇怪的 C++ 访问私有(private)成员问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20578949/

相关文章:

c++ - 如何将 'fixed' floatfield 用于 istream/istringstream?

c++ - 为什么不在operator =中返回const-reference而不是引用?

c++ - Voidcast宏解释

c++ - SIMD:翻转四个压缩整数的符号

c++ - 运行失败(退出值 -1.073.740.940 )

c++ - 如何删除C++中给定矩阵中的特定行和列?

c++ - 尝试在 C++ 中使用递归为模板化多项式类组合类似项

c++ - 将 boost::array<char> 复制到 std::string

c++ - 将指向成员的指针从模板参数包传递给函数对象

c++ - C++ 异构集合调用派生类函数