我需要创建一个Display()方法,它将显示所有属性

时间:2016-05-10 23:44:16

标签: c++

我需要添加一个显示所有属性的display()方法。我不确定如何创建一个输出所有值类型的方法 我尝试使用void Display()但是当我在.cpp文件中定义它时它不允许我返回或使用任何其他值类型。我需要它来显示或调用所有属性,即m_model,m_speed和m_engine_size。

#pragma once

class Car
{
private:
int m_speed;
int Maxspeed;
void turnOnBrakeLight(void);
public:
Car(void);
Car(int Speed);
Car(float engine_size, int speed);

char m_model[50];
float m_engine_size;
void accelerate(void);
void brake(void);
void Setspeed(int setspeed);
int getspeed();
void Setmaxspeed(int Setmaxspeed);
int Getmaxspeed();
};

/

# include "Car.h"
void Car::accelerate(void)
{
m_speed++;
}

void Car::brake(void)
{
m_speed--;
turnOnBrakeLight();
}

void Car::turnOnBrakeLight(void)
{
// turn on brake light
}
void Car::Setspeed(int setspeed)
{
m_speed = setspeed;
}

int Car::getspeed()
{
return m_speed;
}

void Car::Setmaxspeed(int Setmaxspeed)
{
Maxspeed = Setmaxspeed;
}
int Car::Getmaxspeed()
{
return Maxspeed;
}

Car::Car(void)
{
m_speed = 0;
m_engine_size = 0.0f;
m_model[0] = 'N';
m_model[1] = 'o';
m_model[2] = 'n';
m_model[3] = 'e';
m_model[4] = '\0';

}
Car::Car(int speed)
{
m_speed = speed;
m_engine_size = 0.0f;
m_model[0] = 'N';
m_model[1] = 'o';
m_model[2] = 'n';
m_model[3] = 'e';
m_model[4] = '\0';

}
Car::Car(float engine_size, int speed) 
{
m_speed = speed;
m_engine_size = engine_size;
m_model[0] = 'N';
m_model[1] = 'o';
m_model[2] = 'n';
m_model[3] = 'e';
m_model[4] = '\0';
}

Car::Display()
{


}

/

#include <iostream>
#include <conio.h>
#include "Car.h"

using namespace std;

// DECLARE functions
void wait_for_keypress(void);

int main()
{
Car daves_car_1;
Car daves_car_2(55);
Car daves_car_3(2.5, 55);
cout << daves_car_1.m_model << ", " << daves_car_1.m_engine_size << ", " << daves_car_1.getspeed() << endl;
cout << daves_car_2.m_model << ", " << daves_car_2.m_engine_size << ", " << daves_car_2.getspeed() << endl;
cout << daves_car_3.m_model << ", " << daves_car_3.m_engine_size << ", " << daves_car_3.getspeed() << endl;
wait_for_keypress();
}

// DEFINE functions
void wait_for_keypress(void)
{
cout << "Press any key to continue" << endl;
_getch();
}

1 个答案:

答案 0 :(得分:0)

您可以按如下方式创建display方法:

#include <string>

class Car {

private:
    int m_speed;
    int Maxspeed;
    //...
public:
    //...
    std::string display() const {
        return "m_speed = " + m_speed + "\nMaxspeed = " + Maxspeed;
    }

};

我已经在这里定义了它,但你应该像往常一样将定义放在实现文件中。所有这些display方法都返回一个std::string,其中相关的字段变量与Car的实例相关联。然后你可以做

Car _car;
std::cout << _car.display();

显示std::string属性的Car表示。您可以根据需要对此进行扩展以包含所有其他字段,但请注意,char m_model[50]应更改为std::string m_model,以避免混淆指向char类型的指针 - std::string提供“托管”char容器,以便更轻松地操作字符串。

此外,由于您的问题中包含std::cout << car_instance;个代码段,因此确实可能会为用户定义的类型重载operator<<。在这种情况下(例如):

std::ostream& operator<<(std::ostream& _os, const Car& _car) {
    _os << _car.display();
    return _os;
}

[注意流插入/提取操作符是自由函数,因此应在类外定义。]

此重载operator<<允许您在类std::cout的实例上使用ostream(或任何其他Car)。