我需要创建新对象,用控制台中的数据填充它们的字段。该对象包含以下字段:
struct object
{
std::string name;
std::string type;
double x;
double y;
std::time_t time;
double distance() const
{
// Расстояние от точки (0, 0) до объекта
return std::sqrt(
std::pow(x, 2) + std::pow(y, 2)
);
}
};
我读取对象并将其输出到控制台,如下所示:
inline std::ostream& operator<<(std::ostream& os, const object& o)
{
os << "name: " << o.name
<< " type: " << o.type
<< " x: " << o.x
<< " y: " << o.y
<< " time: " << ctime(&o.time);
return os;
}
inline object operator >> (std::istream& is, object& o)
{
object obj;
std::cout << "Enter name: ";
is >> obj.name;
std::cout << std::endl << "Enter x coordinate: ";
is >> obj.x;
std::cout << std::endl << "Enter y coordinate: ";
is >> obj.y;
std::cout << std::endl << "Enter type: ";
is >> obj.type;
obj.time = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
return obj;
}
问题是,当读取然后打印对象时,会输出垃圾或零值:
Enter object data:
Enter name, x coordinate, y coordinate and type: ttt 12.5 12.5 rrr
view::update() called
Added object: name: type: x: 0 y: 0 time: Thu Jan 1 03:00:00 1970
这是为什么?创作日期也很奇怪——一个时代的开始。如何在对象中存储当前日期(这是对象创建的时间)?
添加了一个最小的可重现示例:
#include <string>
#include <chrono>
#include <iostream>
#include <cmath>
#include <ctime>
struct object
{
std::string name;
std::string type;
double x;
double y;
std::time_t time;
double distance() const
{
// Расстояние от точки (0, 0) до объекта
return std::sqrt(
std::pow(x, 2) + std::pow(y, 2)
);
}
};
inline std::ostream& operator<<(std::ostream& os, const object& o)
{
os << "name: " << o.name
<< " type: " << o.type
<< " x: " << o.x
<< " y: " << o.y
<< " time: " << ctime(&o.time);
return os;
}
inline object operator >> (std::istream& is, object& o)
{
object obj;
std::cout << "Enter name, x coordinate, y coordinate and type: ";
is >> obj.name >>
obj.x >>
obj.y >>
obj.type;
obj.time = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
return obj;
}
int main()
{
object obj;
std::cin >> obj;
std::cout << obj;
return 0;
}
那么我们看到了什么?
那些。读取的内容仅返回,但与传递给运算符的参数无关......
那么至少需要写
这样您就可以安全地忽略输入的所有内容......
顺便说一句,运算符通常
>>采用以下形式能够创建链条
简而言之,以下代码
解决了你描述的问题...