[英]Concatenation of String and int types (on declaration!)
我想提供一个唯一的ID号,该ID号等于创建类飞船的对象的时间,因此我尝试了从Java知道的这段代码(但不幸的是,它无法正常工作)
名称是由父类载体继承的,我想要一个可以在GNU c ++编译器中运行的实现(仅用于声明)
#include <iostream>
static int id = 0;
class Ship:private Vehicle
{
Ship()
{
id++;
this->name="Pirate"+id;
}
}
// C++98
Ship() {
std::ostringstream tmp;
tmp << "Pirate" << ++id;
name = tmp.str();
}
// C++11
Ship() : name("Pirate" + std::to_string(++id)) {}
如果数据成员名称的类型为std::string
则可以编写
this->name = "Pirate" + std::to_string( id );
您需要先将int转换为字符串。 将id
替换为std::to_string(id)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.