以下C++无效,因为引用变量需要初始值设定项:
int& a; // illegal
if (isfive) {
a = 5;
} else {
a = 4;
}
Run Code Online (Sandbox Code Playgroud)
但是,MSVC似乎认为这没关系:
int& a = isfive ? 5 : 4;
Run Code Online (Sandbox Code Playgroud)
这意味着MSVC实际上将条件运算符视为单个表达式,而不是将其扩展为if-else语句.
使用条件运算符初始化引用始终是有效的C++吗?
我正在尝试编写我的程序,以便它可以处理StdIn或命令行中指定的文件.
我这样做是通过尝试初始化对a的引用来istream引用cin或ifstream使用条件.
但是当我尝试使用时ifstream,我似乎得到一个错误,即basic_istream move-constructor被声明protected.
istream& refToCIN ( cin ); // This is OK
const istream& refToFile = ifstream(args[1]); // This is OK
const istream& inStream ( FileIsProvided()? ifstream(args[1]) : cin );
// This causes error:
// std::basic_istream<char,std::char_traits<char>>::basic_istream' :
// cannot access protected member declared in class std::basic_istream<char,std::char_traits<char>>
ProcessStream(inStream); // This could either be a file or cin
Run Code Online (Sandbox Code Playgroud)
这可以通过这种方式合理地完成吗?我有一个很好的选择吗?
最佳解释一个例子:
Class banana {
int &yumminess;
banana::banana() {
//load up a memory mapped file, create a view
//the yumminess value is the first thing in the view so
yumminess = *((int*)view);
}
}
Run Code Online (Sandbox Code Playgroud)
但这不起作用:/当我找到"yumminess"引用变量时,我无法知道视图的位置.现在我只是使用一个指针并一直取消引用它,有什么方法可以为我的课程带来一些额外的便利吗?
我有一些代码是正在运行的较大函数的一部分。但是,为了优化它并消除不必要的字符串复制,我想用引用重写此代码。我的代码依赖于GreaterStr是比smallStr更长的字符串。我想用引用重写它,但似乎无法正常工作。如果我尝试在没有显式初始化它们的情况下创建更大的引用和更小的引用,则编译器会告诉我需要在声明时对其进行初始化。如果我尝试将其作为if语句中的临时变量,则最终两个变量都引用同一字符串。
最好的解决方案是什么?
//str1 and str2 are std::strings
std::string largerStr, smallerStr;
if(str1.length() > str2.length()) {
largerStr = str1;
smallerStr = str2;
} else {
largerStr = str2;
smallerStr = str1;
}
Run Code Online (Sandbox Code Playgroud)