C++代码段可以用于MSVC,但不能用于g++

C++ snippet OK with MSVC but not with g++

本文关键字:用于 但不能 g++ MSVC C++ 段可 代码      更新时间:2023-10-16

我是C++的新手,我试图调整一个程序片段,该片段会生成stackoverflow上的"弱组合"或Multiset,但坦率地说,我运行了好几个小时才出现问题。

首先,该程序在MSVC下运行时没有任何抱怨,但在gcc上没有。

重点是,我在stackoverflow上读过很多类似这样的文章,关于gcc和msvc的不同行为,我已经理解,msvc在处理这种情况时更"自由",而gcc更"严格"。我也理解,不应该"将一个非常数引用绑定到一个临时(内部(变量。">

但我很抱歉,我无法修复它,也无法让这个程序在gcc下工作——从几个小时以来。

如果可能的话,还有第二个问题:我必须引入一个全局变量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;
}

C++要求对未命名临时(如string()(的引用参数必须是const引用r值引用

这两种引用类型中的任何一种都可以保护您不修改您没有意识到将在当前表达式中销毁的变量。

根据您的需要,它可以将其作为一个值参数:

string ListMultisets( ... string strOut = string() ... ) {

或者它可以使它成为一个函数局部变量:

string ListMultisets(...) {
string strOut;

在您的示例程序中,任何一个更改都可以。

删除strOut参数的默认值。

在main中创建一个字符串并将其传递给函数。

将函数的返回类型更改为int。

将total设为局部变量ListMultiset((。返回total而不是strOut(您将返回字符串值strOut作为参考参数。(

新ListMultiset的签名看起来像:

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;
}