Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/147.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 异常处理C++_xcode_C++_Xcode_Exception Handling - Fatal编程技术网

C++ 异常处理C++_xcode

C++ 异常处理C++_xcode,c++,xcode,exception-handling,C++,Xcode,Exception Handling,以下代码在Visual Studio 2010中完全可以引发异常: #include <iostream> #include <cmath> using namespace std; int perfectSquare(double sq, int nu); int main() { double num; double sq

以下代码在Visual Studio 2010中完全可以引发异常:

        #include <iostream>
        #include <cmath>
        using namespace std;

        int perfectSquare(double sq, int nu);

        int main()
        {
            double num;
            double squareRoot;
            int perfectSq;

            cout << "Enter the a number: ";
            cin >> num;

            try
            {
                squareRoot = sqrt(num); 
                perfectSq = perfectSquare(squareRoot, num);
                cout << "The square root is: " << perfectSq << endl;
            }

            catch(char * exceptionString)
            {
                cout << exceptionString;
            }

            cout << "BYE." << endl;
        //  system("PAUSE");
            return 0;
        }


        int perfectSquare(double sq, int nu)
        {
            int temp = sq;
            if (sq != temp)     //clever test; if square root IS NOT an INT
            {
                throw "not a perfect square.\n";
            }
            else
            {
                return sq;
            }
        }
#包括
#包括
使用名称空间std;
int perfectSquare(双sq,int nu);
int main()
{
双数;
双平方根;
int perfectSq;
cout>num;
尝试
{
平方根=sqrt(num);
perfectSq=perfectSquare(平方根,num);

cout您抛出的是一个字符串文本,在XCode中它似乎是一个
const char*
,而不是
char*
您实际上没有抛出
char*
,而是抛出了一个
const char*
。将异常捕获更改为

catch(const char * exceptionString)
它应该会起作用


<所有C++中的文字字符串都相当于指向一个常量字符串的指针,即“代码> const char *//>代码> ./p>快速修复。没有意识到这与V.S.的区别。谢谢。是的,它不应该在VisualStudio中工作。我喜欢Xcode更严格,因为忽略这个错误是错误的。实际上,字符串文字是类型为
char[N]
,主要是出于历史原因。但您应该将其视为
const char[N]
。因此,一方面,XCode的行为似乎不正确,但另一方面,无论如何,您应该捕获
const char*