[英]Classes in C++: Declaring an Instance
I have consulted many websites but have not successfully completed my code. 我咨询了很多网站,但没有成功完成我的代码。
I am trying to write some code that spits out information about a car, once the user provides information. 我试图写一些代码,一旦用户提供信息,就会吐出有关汽车的信息。 After compiling, the compiler says that "declaration does not declare anything." 编译后,编译器说“声明没有声明任何内容”。 Here's the code: 这是代码:
#include <iostream>
#include <string>
#include "Car.h"
using namespace std;
Car::Car()
{
}
void Car::accel()
{
speed += 5;
}
void Car::brake()
{
speed -= 5;
}
void Car::setSpeed(int newSpeed)
{
speed = newSpeed;
}
int Car::getSpeed()
{
return speed;
}
void Car::setMake(string newMake)
{
make = newMake;
}
string Car::getMake()
{
return make;
}
void Car::setYearModel(int newYearModel)
{
yearModel = newYearModel;
}
int Car::getYearModel()
{
return yearModel;
}
int main()
{
Car auto; //instance of class Car
int autoYear; //year of auto
string autoMake; //make of auto
int autoSpeed; //speed of auto
cout << "Enter the year model of your car. ";
cin >> autoYear;
cout << "Enter the make of your car. ";
cin >> autoMake;
auto.setYear(autoYear); //stores input year
auto.setMake(autoMake); //stores input make
}
And the header, Car.h: 标题,Car.h:
#include <iostream>
#include <string>
using namespace std;
#ifndef CAR_H
#define CAR_H
class Car
{
private:
int yearModel;
string make;
int speed;
public:
Car();
void accel();
void brake();
void setSpeed(int newSpeed);
int getSpeed();
void setMake(string newMake);
string getMake();
void setYearModel(int newYearModel);
int getYearModel();
};
#endif
I also have errors for missing semicolons every time my object auto appears ("expected ; before auto" and "expected primary-expression before auto"). 每次我的对象自动出现时(“预期;在auto之前”和“在auto之前预期的primary-expression”),我也会错误地丢失分号。 What could be the problem? 可能是什么问题呢?
auto
is a keyword. auto
是一个关键字。 You'll need to pick a different name. 你需要选择一个不同的名字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.