C ++:可以使用具有相同参数的私有构造函数重载构造函数吗?

时间:2013-02-04 01:28:30

标签: c++ class constructor overloading

可以使用具有相同参数的私有构造函数重载构造函数吗?

基本上如果某些东西存储一个正整数,那么在公共构造函数中它将确保存储一个正整数,而在私有构造函数中它不会执行检查。

显然,这个例子并不是一个合适的用途,但有时你想在一个方法中创建一个对象,你不希望它浪费时间进行完全安全的初始化;您可能只想告诉它在没有特殊检查的情况下立即创建一些东西(或者更谨慎的堆分配或者更昂贵的东西),当您稍后再次执行它们或者它们只是不必要时,类中的方法应该是能够自动使用此构造函数而不是具有相同参数的其他公共构造函数。

3 个答案:

答案 0 :(得分:2)

不,您不能使用私有构造函数或其他成员函数重载:只有名称和参数类型才能用于重载解析。

要执行您要查找的内容,请定义一个私有构造函数,该构造函数采用额外的bool参数来指示需要执行参数检查:

class A {
public:
    A(int x) : A(x, true) {}
private:
    A(int x, bool check) {
        if (check) {
            // Perform the check of the x argument
        }
    }
};

构造实例并绕过检查,可以访问私有构造函数的函数调用

A aUnchecked(-123, false);

检查实例以通常的方式构建:

A aChecked(123);

答案 1 :(得分:2)

你不能像私人对象那样过载重叠,但你可以重载签名:参数的数量及其类型。

私人建筑师很常见。

一种用法是逻辑上“删除”的构造函数(最后由C ++ 11直接支持),另一种用于公共工厂函数。


示例:

class A
{
public:
    A( int const x)
    {
        // Whatever, checked construction.
        // Perform the check of the x argument.
        // Then other things.
        // In C++11 it can be done by checking x and forwarding to the
        // unchecked constructor in the same class. Not shown here though.
    }

private:
    enum unchecked_t { unchecked };
    A( int const x, unchecked_t )
    {
        // Unchecked construction.
    }

    // Methods that possibly use the unchecked constructor.
};

答案 2 :(得分:1)

使用私有构造函数,你不能直接实例化一个类,而是使用一个名为Constructor Idiom的东西。

其他事情你不能继承该类,因为想要继承的类将无法访问构造函数

你应该做的就是从构造函数中调用w amethode来检查

相关问题