gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:57:20 25 4
gpt4 key购买 nike

我正在尝试使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com