c++ - 从用户定义类型到 int 的词法转换

标签 c++ boost

我正在尝试使用 boost::lexical_cast 将我的用户定义类型转换为整数。 但是,我得到一个异常(exception)。我错过了什么??

class Employee {
private:
    string name;
    int empID;

public:
    Employee() : name(""), empID(-1)
    { }

    friend ostream& operator << (ostream& os, const Employee& e) {
        os << e.empID << endl;      
        return os;
    }
    /*
    operator int() {
        return empID;
    }*/
};

int main() {
    Employee e1("Rajat", 148);
    int eIDInteger = boost::lexical_cast<int>(e1); // I am expecting 148 here.
    return 0;
}

我知道我总是可以使用转换运算符,但只是想知道为什么词法转换在这里不起作用。

最佳答案

问题是您插入到输出流中的不是整数表示(因为尾随 << std::endl )。以下以类似的方式失败:

boost::lexical_cast<int>("148\n")

删除 << std::endl让它工作:

friend std::ostream& operator << (std::ostream& os, const Employee& e) {
    os << e.empID;
//  ^^^^^^^^^^^^^^
//  Without << std::endl;

    return os;
}

关于c++ - 从用户定义类型到 int 的词法转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16494924/

相关文章:

c++ - 因未执行的代码而崩溃

c++ - 使用 shared_ptr 和 weak_ptr 时避免间接循环引用

c++11 - 如何在 boost 1.55 中使用 boost::split 和 boost::string_ref

c++ - 为什么我不能在我的三元表达式中使用 return 但我可以在常规的 if-else 语句中使用?

c++ - 减去两个对象的无序 std::vector

c++ - 可以在折叠表达式中使用子表达式吗?

c++ - Win32 C++ 从元素中获取文本

c++ - 为 C++/Boost 库(netbeans 或 eclipse)设置环境

c++ - 最低共同祖先( boost 图)

c++ - 如何使用 mpl 技术启用构造函数