我对C++很新,这是我的情况.我有一个参考MyOjbect,但确切的对象取决于条件.所以我想做这样的事情:
MyObject& ref;
if([condition])
ref = MyObject([something])
else
ref = MyObject([something else]);
Run Code Online (Sandbox Code Playgroud)
我现在不能这样做,因为编译器不允许我声明但不初始化引用.我能做些什么来实现我的目标?
我习惯于编写带有文件名或读取的小命令行工具std::cin,所以我一直在使用这种模式:
int main(int argc, char* argv[])
{
std::string filename;
// args processing ...
std::ifstream ifs;
if(!filename.empty())
ifs.open(filename);
std::istream& is = ifs.is_open() ? ifs : std::cin;
std::string line;
while(std::getline(is, line))
{
// process line...
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在阅读Stack Overflow上的一个问题之后,我尝试修改我常用的模式,以满足从文件或文件中读取的需要std::istringstream.令我惊讶的是它不会编译并给出这个错误:
Run Code Online (Sandbox Code Playgroud)temp.cpp:164:47: error: invalid initialization of non-const reference of type ‘std::istream& {aka std::basic_istream<char>&}’ from an rvalue of type ‘void*’ std::istream& is = ifs.is_open() ? ifs : iss; // won't compile
在我看来,它试图将std::istringstreamobject(iss)转换为布尔值并获取它operator void*(). …
大家问候!
检查我自己的代码,我走到了这个有趣的路线:
const CString &refStr = ( CheckCondition() ) ? _T("foo") : _T("bar");
Run Code Online (Sandbox Code Playgroud)
现在我完全不知所措,无法理解为什么它是合法的.据我所知,必须使用r值或l值初始化const引用.未初始化的引用不可存在.但是()?operator在为引用赋值之前执行CheckCondition()函数.我现在可以看到,当执行CheckCondition()时,refStr存在,但仍未初始化.如果CheckCondition()将抛出异常,或使用goto语句传递控件,会发生什么?它是否会使参考文献未初始化或者我遗漏了什么?