2014-01-13 14 views
0

我有这样的:如何通过包含要打印的字符串的类函数来打印异常?

catch (Except& e) { 
    std::cout << e.print() << std::endl; 
} 

我想这对打印:OK you won!

所以我有类:

class Except{ 
public: 
    std::string print() { 
    std::string error("OK you won!\n"); 
    return error; 
    } 
}; 

我有这样的错误在除类:"'string' in namespace 'std' does not name a type"

+3

'但它不工作...'什么不工作? – Paranaix

+0

是否有错误讯息? – tofutim

+9

每次你用“不工作”来解释你的问题时,程序员就会死亡。 – Shoe

回答

0

查看下面的代码:

#include <iostream> 
#include <string> 

class Except{ 
     public: 
       std::string stack() { 
         std::string error("OK you won!\n"); 
         return error; 
       } 
}; 

int main() { 
     try { 
       throw Except(); 
     } catch (Except &e) { 
       std::cout << e.stack() << std::endl; 
     } 
     return 0; 
} 

输出是:

./a.out 
OK you won! 
+3

你忘了'#include '(就像OP一样,很有可能)。 –

+0

@AndyPowl如果他没有包含iostream,没有人会真正关心这个:D – Paranaix

+0

Yeap,但它通过iostream头部包含。 – vershov

0

你可能不会把它扔正确的 - 为我的作品:

#include <iostream> 
#include <string> 

class Except{ 
    public: 
    std::string stack() { 
     std::string error("OK you won!\n"); 
     return error; 
    } 
}; 

int main() { 

    try { 
    throw Except(); 
    } catch (Except& e) { 
    std::cout << e.stack() << std::endl; 
    } 

    return 0; 
}; 

输出:

OK you won!

+1

同样的故事:)你忘了'#include ' –

+0

啊真的,tx。似乎gcc工作正常。 – naumcho

3

你必须包括std::string的标题:#include <string>