So, I've got a class Car:
car.h
#ifndef CAR_H
#define CAR_H
#include <iostream>
#include <string.h>
#include "car.cpp"
// Car class with its attributes
class Car {
public:
std::string brand;
std::string model;
int year;
// Constructor
Car(int year, std::string model, std::string brand);
};
#endif
and I wanted to make a class constructor definition outside the class in another .cpp file:
car.cpp
#include <string.h>
Car::Car(int year, std::string model, std::string brand)
{
this->brand = brand;
this->model = model;
this->year = year;
}
I tried to compile, but this error has occurred:
car.cpp:3:1: error: ‘Car’ does not name a type
Why it happened and how to fix it?
My main.cpp:
#include <iostream>
#include "car.h"
using namespace std;
int main() {
// Create an object of Car
Car carObj1 = Car(1992, "model X", "Brand1");
// Create another object of Car
Car carObj2 = Car(2003, "model Y", "Brand2");
// Print attribute values
cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
return 0;
}
You got the includes the wrong way round. car.cpp should #include "car.h" not the other way around.
Also the correct header file for std::string is <string> not <string.h>
Also member initialisation is better done with initialiser lists not assignment
Car::Car(int year, std::string model, std::string brand) :
brand(brand), model(model), year(year)
{
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With