所以我是一名從事例外處理專案(Try/catch)的 CS 學生。我的老師告訴我們要實作 sstream 庫,這樣我們就可以在輸出包含 int 型別傳遞引數的訊息的類中使用它。由于某種我不知道的原因,當我使用它時,甚至當我宣告一個 stringstream 型別的變數時,它會導致編譯錯誤并顯示錯誤訊息:
“'tornadoException' 的復制建構式被隱式洗掉,因為欄位 'ss' 有一個已洗掉的復制建構式”
這是我的代碼。我很茫然。
主程式
#include <iostream>
#include <string>
#include <sstream>
#include "tornadoException.h"
using namespace std;
int main()
{
try{
int tornado = 0;
cout << "Enter distance of tornado: ";
cin >> tornado;
if(tornado > 2){
throw tornadoException(tornado);
}
else{
throw tornadoException();
}
}
catch(tornadoException tornadoObj){
cout << tornadoObj.what();
}
}
龍卷風例外.cpp
#include <iostream>
#include <string>
#include <sstream>
#include "tornadoException.h"
using namespace std;
tornadoException::tornadoException(){
message = "Tornado: Take cover immediately!";
}
tornadoException::tornadoException(int m){
ss << "Tornado: " << m << "miles away!; and approaching!";
message = ss.str();
}
string tornadoException::what(){
return message;
}
龍卷風例外.h
#ifndef tornadoException_h
#define tornadoException_h
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
class tornadoException{
public:
tornadoException();
tornadoException(int m);
string what();
private:
stringstream ss;
string message;
};
#endif
uj5u.com熱心網友回復:
stringstream 有一個洗掉的復制建構式,這意味著一個 stringstream 物件不能被復制。
由于您的 tornadoException 類有一個 stringstream 變數,這意味著您的類也不能被復制。
在您的主函式中,您按值捕獲例外,這意味著您將其復制到tornadoObj變數中 - 這是不允許的。
嘗試將行更改為
catch(tornadoException tornadoObj),catch(tornadoException& tornadoObj)以便您獲得對例外的參考而不是它的副本。
這實際上是一個通用規則:例外應始終通過參考而不是通過復制來捕獲:核心準則 E.15
uj5u.com熱心網友回復:
好的,找出錯誤,但我會留下這篇文章,因為我在其他地方找不到答案。問題是我將 stringstream 緩沖區宣告為類中的私有變數。緩沖區需要在使用它的函式宣告中在本地宣告,在這種情況下,就在實作檔案中加載緩沖區之前:
tornadoException::tornadoException(int m){
stringstream ss;
ss << "Tornado: " << m << " miles away!; and approaching!";
message = ss.str();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/330389.html
