我在java中使用过它们,似乎没有太多问题,但在C++中我并没有很好地掌握它们。任务是:
Write a class named Car that has the following member variables:
year. An int that holds the car's model year.
make. A string that holds the make of the car.
speed. An int that holds the car's current speed.
In addition, the class should have the following member functions.
Constructor. The constructor should accept the car's year and make
as arguments and assign these values to the object's year and
make member variables. The constructor should initialize the
speed member variable to 0.
Accessors. Appropriate accessor functions should be created to allow
values to be retrieved from an object's year, make, and speed
member variables.
accelerate. The accelerate function should add 5 to the speed member
variable each time it is called.
brake. The brake function should subtract 5 from the speed member
variable each time it is called.
Demonstrate the class in a program that creates a Car object, and then
calls the accelerate function five times. After each call to the
accelerate function, get the current speed of the car and display
it. Then, call the brake function five times. After each call to
the brake function, get the current speed of the car and display it.到目前为止,这就是我所拥有的,但我相当确定我完全错了。如果有人有任何建议,我将不胜感激,谢谢!
#include<iostream>
#include<string>
using namespace std;
class Car
{
public:
int year;
string make;
int speed;
Car()
{
setYear(newYear);
setMake(newMake);
setSpeed(0);
}
void setYear(int newYear)
{
year = newYear;
}
void setMake(string newMake)
{
make = newMake;
}
int getYear()
{
return year;
}
string getMake()
{
return make;
}
int accelerate(int speed)
{
return (speed+5);
}
int brake(int speed)
{
return (speed-5);
}
};
int main()
{
return 0;
}PS: main的返回值为0;纯粹是一个占位符,只是想要理解整个"get and set“的东西。
发布于 2010-02-09 12:17:14
一般来说,get/set函数应该可以很好地工作。其他一些评论:
year,make和speed变量可能应该是私有的,否则就不需要为它们设置任何get/set函数,因为变量也可以改变,因为根本不应该有任何set函数。我不认为有可能更改directly.make或设置car directly.newYear和newMake作为parameters.accelerate(),而speed应更改保存在car对象中的代码,而不仅仅是返回不同于car的值可以将许多意外名称导入全局命名空间,并且通常最好使用std::string这样的显式限定名称。发布于 2010-02-09 12:11:27
我看到了一些问题:
您引用的是构造函数中未传递给构造函数的变量(newYear、newMake)
accelerate和decelerate函数不会修改任何状态;它们只是从传入的速度中加减5-我认为它们不应该这样做。请注意,问题描述中说它们在speed 成员变量中添加/减去。
所有的成员变量都是公共的。你会在Java中这样做吗?
发布于 2010-02-09 12:11:55
您可能希望将内部变量设置为私有,因为它们只能由类中的方法更新。其次,您需要构造函数的参数,以便您可以设置年份和进行初始设置。
例如:
public: Car(int newYear, string newMake) {...}
class Car
{
private:
int year;
string make;
int speed;
public:
Car(int newYear, string newMake)
{
setYear(newYear);
setMake(newMake);
setSpeed(0);
}
...
}您也没有更新accelerate和brake方法上的速度值。尝试:
return (speed -=5);或
return (speed += 5);https://stackoverflow.com/questions/2226675
复制相似问题