构造函数参数检查 [英] checking of constructor parameter

查看:125
本文介绍了构造函数参数检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class item
{
    int i;

  public:
    item(int no) {

    }
};

我想检查构造函数参数。如果发现持有负值,则应停止对象创建。

I want to check the constructor parameter. If it is found to hold a negative value, then object creation should be stopped.

此处不能使用异常,因为目标系统不支持异常。

Exceptions can not be used here as the targeted system does not support exceptions.

推荐答案

没有办法停止创建一个对象而不抛出。你最好做的是设置一个无效的参数标志,你必须检查后,如果真正丢弃对象而不使用它。

There is no way to stop the creation of an object without throwing. The best you can do is set an "invalid parameter" flag that you have to check afterwards, and if true discard the object without using it.

,可能最好使用工厂方法来创建对象 - 这样,您可以在调用构造函数之前进行检查:

With the requirements you have, it would probably be better to use a factory method to create the objects -- this way, you can make the checks before calling the constructor:

class item
{
    int i;
public:
    static item* create(int no) {
        if (no < 0) {
            return 0;
        }

        return new item(no);
    }

private:
    item(int no) {

    }
};

您可以使用

item* myItem = item::create(-5);
if(!myItem) {
    // failed
}

但是,这迫使您在堆上分配所有实例。

However, this forces you to allocate all item instances on the heap.

这篇关于构造函数参数检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆