[英]C++ snippet OK with MSVC but not with g++
我是 C++ 的新手,我尝试改编一个程序片段,该片段会生成“弱组合”或在stackoverflow上找到的 Multisets,但我运行 - 坦率地说 - 几个小时以来的问题。
首先,该程序在 MSVC 下运行时没有任何抱怨 - 但不是在 gcc 上。
关键是,我已经在stackoverflow上阅读了很多类似这样的文章,关于 gcc 和 msvc 的不同行为,我明白,msvc 在处理这种情况时更“自由”,而 gcc 更“严格” ”。 我也明白,不应“将非常量引用绑定到临时(内部)变量”。
但是很抱歉,我无法修复它并使该程序在 gcc 下工作 - 又是几个小时以来。
并且 - 如果可能的话 - 第二个问题:我必须引入一个全局变量total
,尽管它运行良好,但据说它是“邪恶的”。 我需要这个 total 值,但是我找不到具有非全局范围的解决方案。
非常感谢大家的帮助。
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int total = 0;
string & ListMultisets(unsigned au4Boxes, unsigned au4Balls, string & strOut = string(), string strBuild = string()) {
unsigned au4;
if (au4Boxes > 1) for (au4 = 0; au4 <= au4Balls; au4++)
{
stringstream ss;
ss << strBuild << (strBuild.size() == 0 ? "" : ",") << au4Balls - au4;
ListMultisets(au4Boxes - 1, au4, strOut, ss.str());
}
else
{
stringstream ss;
ss << mycount << ".\t" << "(" << strBuild << (strBuild.size() == 0 ? "" : ",") << au4Balls << ")\n";
strOut += ss.str();
total++;
}
return strOut;
}
int main() {
cout << endl << ListMultisets(5,3) << endl;
cout << "Total: " << total << " weak compositions." << endl;
return 0;
}
删除 strOut 参数的默认值。
在 main 中创建一个字符串并将其传递给函数。
将函数的返回类型更改为 int。
总计一个局部变量 ListMultisets()。 返回 total 而不是 strOut (您将字符串值 strOut 作为参考参数返回。)
新 ListMultisets 的签名将如下所示:
int ListMultisets(unsigned au4Boxes, unsigned au4Balls, string & strOut)
我会让你弄清楚实现。 它要么很容易,要么很有教育意义。
您的新主函数将如下所示:
int main() {
string result;
int total = ListMultisets(5,3, result);
cout << endl << result << endl;
cout << "Total: " << total << " weak compositions." << endl;
return 0;
}
C++ 要求未命名临时对象的引用参数(如string()
)必须是const
引用或r 值引用。
这两种引用类型中的任何一种都可以保护您免于修改您没有意识到将在当前表达式中销毁的变量。
根据您的需要,可以将其设为值参数:
string ListMultisets( ... string strOut = string() ... ) {
或者它可以使它成为函数局部变量:
string ListMultisets(...) {
string strOut;
在您的示例程序中,任何一种更改都有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.