Jos*_*osh 3 c++ constructor class object instantiation
如果实例化中存在错误,是否有办法停止C++类?比如,返回NULL可能吗?基本上我有一个MySQL的包装类,构造函数进行连接,但如果连接失败,我希望对象是,嗯,没用?
PDB::PDB(string _DB_IP, string _DB_USER, string _DB_PASS, string _DB_DB)
: _DB_IP( _DB_IP ), _DB_USER( _DB_USER ), _DB_PASS( _DB_PASS ), _DB_DB( _DB_DB )
{
mysql_init(&this->mysql);
this->connection = mysql_real_connect(&this->mysql, this->_DB_IP.c_str(), this->_DB_USER.c_str(), this->_DB_PASS.c_str(), this->_DB_DB.c_str(), 0, 0, 0);
if( this->connection == NULL ) // WHAT SHOULD I DO HERE, OTHER THAN THROW AN ERROR?
{
cout << mysql_error(&this->mysql) << endl;
}
this->result = NULL;
}
Run Code Online (Sandbox Code Playgroud)
我应该怎么做NULL测试,停止创建等?
Fre*_*son 10
抛出异常实际上是在构造期间指示错误的唯一方法.
http://www.parashift.com/c++-faq-lite/exceptions.html#faq-17.8
如果连接通常会失败,请在对象中设置一个标志,并为该类提供is_connected()成员函数,并在应用程序代码中使用它.如果通常不能失败,则抛出异常.前者是C++标准库用于打开文件流的模式.