简体   繁体   English

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

[英]lexical cast from user defined type to int

I am trying to use boost::lexical_cast to convert my user defined type into an integer. 我正在尝试使用boost :: lexical_cast将用户定义的类型转换为整数。 However, I get an exception. 但是,我例外。 What am I missing?? 我想念什么?

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

I know I can always use the conversion operator, but just wondering why lexical cast doesn't work here. 我知道我总是可以使用转换运算符,但是想知道为什么词法转换在这里不起作用。

The problem is that what you insert into the output stream is not the representation of an integer (because of the trailing << std::endl ). 问题在于,您插入到输出流中的不是整数的表示形式(由于尾随<< std::endl )。 The following fails in a similar way: 以下内容以类似的方式失败:

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

Removing the << std::endl makes it work: 删除<< std::endl使其起作用:

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

    return os;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM