从catch块调用异常类中的函数并不是打印从try块传递的值

calling a function in the exception class from catch block is not printing a value that is passed from try block

本文关键字:try 打印 并不是 函数 异常 catch 调用      更新时间:2023-10-16

我在catch块的异常类中调用了一个函数what(),但在what()中,函数正在打印垃圾值,因为它没有被分配任何值,而应该打印checkusername()函数抛出的值,但它没有这样做,请帮我。这是代码

#include <iostream>
#include <string>
#include <sstream>
#include <exception>
using namespace std;
class BadLengthException
{
public:
int n1;
BadLengthException(int n)
 {
    n1=n;
  }
int what()
    {
    cout << n1;
    }
};
bool checkUsername(string username) {
bool isValid = true;
int n = username.length();
if(n < 5) {
    throw BadLengthException(n);
}
for(int i = 0; i < n-1; i++) {
    if(username[i] == 'w' && username[i+1] == 'w') {
        isValid = false;
    }
}
return isValid;
}
int main() {
int T; cin >> T;
while(T--) {
    string username;
    cin >> username;
    try {
        bool isValid = checkUsername(username);
        if(isValid) {
            cout << "Valid" << 'n';
        } else {
            cout << "Invalid" << 'n';
        }
    } catch (BadLengthException e) {
        cout << "Too short: " << e.what() << 'n';
    }
 }
 return 0;
 }

what没有return语句,因此导致了未定义的行为。我想你应该用return n1而不是cout << n1