我有一个Aircraft
班。我想循环更新飞机对象的属性(每秒钟更新一次)。
如何在不创建新对象的情况下更新这些属性?我应该使用指针吗?我的目标:每隔一秒钟更新飞机信息
我的代码:
class Aircraft
{
public:
unsigned int altitude, speed, direction;
Aircraft(unsigned int aAltitude, unsigned int aSpeed, unsigned int aDirection)
{
altitude = aAltitude;
speed = aSpeed;
direction = aDirection;
}
};
int main()
{
//aircraft's initial values
Aircraft myAircraft(0, 10, 345);
//Initial values should are printed
cout << myAircraft.altitude + "," + myAircraft.speed + "," + myAircraft.direction << endl; //print initial values
//In this loop new values for altitude, speed and direction should be assigned
for (int i = 0; i < 10; i++)
{
//aircraft's new values
Aircraft myAircraft(new altitude, new speed, new direction);
//print updated attributes
cout << myAircraft.altitude + "," +
myAircraft.speed "," myAircraft.direction
<< endl << endl; //print new values
}
}
结果应如下所示:(值无关紧要)
0, 10, 345
0, 30, 345
0, 60, 345
0, 100, 345
0, 150, 345
300, 180, 345
700, 220, 345
2000, 250, 345
答案 0 :(得分:2)
如何在不创建新对象的情况下更新这些属性?
在循环外创建一个Aircraft
,并使用该类的setter functions(建议将类资源设置为private
)来设置该类中的每个属性。
我应该使用指针吗?
为了给出解释,相当不,因为您只想在类属性中打印每个更新,所以不需要动态内存分配。
关于每次更新后打印元素,通常的C ++惯例是 overload operator<<
,这使您可以方便地编写:
std::cout << aircraft_object;
示例代码如下:(See Live)
#include <iostream>
using uint32 = unsigned int;
class Aircraft /* final */
{
private: // private attributes
uint32 altitude, speed, direction;
public:
// provided default arguments, so that default-construction is possible
Aircraft(uint32 aAltitude = 0, uint32 aSpeed = 0, uint32 aDirection = 0)
: altitude{ aAltitude }
, speed{ aSpeed }
, direction{ aDirection }
{}
// provide setters
void setAltitude(const uint32 alti) noexcept { altitude = alti; }
void setSpeed(const uint32 sp) noexcept { speed = sp; }
void setDirection(const uint32 dir) noexcept { direction = dir; }
// non-member function(s): operator<< overload
friend std::ostream& operator<<(std::ostream& out, const Aircraft& obj) noexcept;
};
std::ostream& operator<<(std::ostream& out, const Aircraft& aircraft) noexcept
{
return out << aircraft.altitude << ", " << aircraft.speed
<< ", " << aircraft.direction << '\n';
}
int main()
{
Aircraft aircraft_obj{}; // constructed with intial values {0, 0,0}
for (auto i = 0; i < 3; ++i)
{
uint32 alti, sp, dir;
// get the user inputs
std::cin >> alti >> sp >> dir;
// set the attributes
aircraft_obj.setAltitude(alti);
aircraft_obj.setSpeed(sp);
aircraft_obj.setDirection(dir);
// print out the object
std::cout << aircraft_obj;
}
return 0;
}
输入:
0 10 345
0 30 345
0 60 345
输出:
0, 10, 345
0, 30, 345
0, 60, 345
答案 1 :(得分:1)
您可以使用.
运算符轻松地修改非常量对象的值。
myAircraft.altitude = newAltitude;
myAircraft.speed = newSpeed;
myAircraft.direction = newDirection;
cout << myAircraft.altitude << ", " << myAircraft.speed << ", " << myAircraft.direction << '\n';
P.S。通过将字符串与+
连接来打印字符串是一种非常不好的做法。
而是使用如上所述的<<
运算符。
在您的情况下,该代码甚至无效,因为您正尝试在字符串中添加数字。符合逻辑的正确方法是首先将数字转换为字符串to_string(myAircraft.altitude) + ", "
。
此外,避免使用endl
,因为它不必要地刷新缓冲区。好处可以在这里看到:Benchmark。