gpt4 book ai didi

c++ - 如何使用运算符<<打印类对象

转载 作者:可可西里 更新时间:2023-11-01 15:53:28 25 4
gpt4 key购买 nike

我想为 AutoData 类编写一个打印函数,其中包含有关汽车的信息。使用此打印功能,理想情况下我想打印出一个包含许多不同类对象的 vector 。我已经为对象的每个元素编写了 get 函数,但我仍然不确定如何使用这些函数编写一个函数来以下列格式打印出数据:

mpg:cylinders:displacement:horsepower:weight:acceleration:modelYear:origin:carName

例如:

10.0:8:360.0:215.0:4615.:14.0:70:1:ford f250
10.0:8:307.0:200.0:4376.:15.0:70:1:chevy c20
11.0:8:318.0:210.0:4382.:13.5:70:1:dodge d200

类是:

#include <string>
#include <vector>
#include <iostream>

using namespace std;

class AutoData {

public:
AutoData()
{
mpg = 0;
cylinders = 0;
displacement = 0;
horsepower = 0;
weight = 0;
acceleration = 0;
modelYear = 0;
origin = 0;
carName = "";
}

AutoData( const AutoData & rhs)
{
setAuto(rhs.mpg, rhs.cylinders, rhs.displacement, rhs.horsepower, rhs.weight, rhs.acceleration, rhs.modelYear, rhs.origin, rhs.carName);
}

void setAuto(float mp, int cy, float di, float ho, float we, float ac, int mo, int o, string ca)
{
mpg = mp;
cylinders = cy;
displacement = di;
horsepower = ho;
weight = we;
acceleration = ac;
modelYear = mo;
origin = o;
carName = ca;
}

const float & getmpg( ) const
{
return mpg;
}

const int & getcylinders( ) const
{
return cylinders;
}

const float & getdisplacement( ) const
{
return displacement;
}

const float & gethorsepower( ) const
{
return horsepower;
}

const float & getweight( ) const
{
return weight;
}

const float & getacceleration( ) const
{
return acceleration;
}

const int & getmodelYear( ) const
{
return modelYear;
}

const int & getorigin( ) const
{
return origin;
}

const string & getcarName( ) const
{
return carName;
}

bool operator == (const AutoData & rhs ) const
{
if( getmpg( ) == rhs.getmpg( ) )
{
return gethorsepower( ) == rhs.gethorsepower( );
}

else
{
return false;
}
}

bool operator > ( const AutoData & rhs ) const
{
if( rhs.getmpg( ) > getmpg( ) )
{
return true;
}

else if( getmpg( ) == rhs.getmpg( ) )
{
if( rhs.gethorsepower( ) > gethorsepower( ) )
{
return true;
}
}

else
{
return false;
}
}


private:
float mpg;
int cylinders;
float displacement;
float horsepower;
float weight;
float acceleration;
int modelYear;
int origin;
string carName;
};

任何人都可以提供任何帮助/建议,我们将不胜感激!!谢谢

最佳答案

如果你想能够做到std::cout << AutoData(); , 你需要重载输出流运算符 operator<< :

std::ostream& operator<< (std::ostream &out, AutoData const& data) {
out << data.getmpg() << ':';
out << data.getcylinders() << ':';
// and so on...
return out;
}

此函数不是成员函数,并且由于每个属性都有 getter,因此不必将此函数声明为 friend你类的。

然后你可以这样做:

AutoData myAuto;
std::cout << myAuto << '\n';

关于c++ - 如何使用运算符<<打印类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23239646/

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