[英]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.