相关疑难解决方法(0)

使用条件运算符初始化引用变量

以下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++吗?

c++ reference ternary-operator

7
推荐指数
3
解决办法
6184
查看次数

初始化对istream的引用

我正在尝试编写我的程序,以便它可以处理StdIn或命令行中指定的文件.

我这样做是通过尝试初始化对a的引用来istream引用cinifstream使用条件.

(此处此处描述类似的技术)

但是当我尝试使用时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)

这可以通过这种方式合理地完成吗?我有一个很好的选择吗?

c++ reference

7
推荐指数
1
解决办法
798
查看次数

以后可以初始化引用变量吗?

最佳解释一个例子:

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"引用变量时,我无法知道视图的位置.现在我只是使用一个指针并一直取消引用它,有什么方法可以为我的课程带来一些额外的便利吗?

c++

3
推荐指数
1
解决办法
565
查看次数

有条件地将std :: string分配为引用

我有一些代码是正在运行的较大函数的一部分。但是,为了优化它并消除不必要的字符串复制,我想用引用重写此代码。我的代码依赖于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)

c++

1
推荐指数
1
解决办法
64
查看次数

标签 统计

c++ ×4

reference ×2

ternary-operator ×1