如何通过包含要打印的字符串的类函数打印异常?

时间:2014-01-13 18:12:11

标签: c++ exception cout

我有这个:

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;
  }
};

我在Except类中遇到此错误:"'string' in namespace 'std' does not name a type"

3 个答案:

答案 0 :(得分:3)

您必须包含std::string的标头:#include <string>

答案 1 :(得分: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!

答案 2 :(得分: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!