简体   繁体   English

如何在另一个文件中的类之外定义类构造函数?

[英]How to define class constructor outside class in another file?

So, I've got a class Car:所以,我有一个类 Car:

car.h汽车.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:我想在另一个 .cpp 文件中的类之外创建一个类构造函数定义:

car.cpp汽车.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:我的 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. car.cpp 应该#include "car.h"而不是相反。

Also the correct header file for std::string is <string> not <string.h> std::string的正确头文件也是<string>而不是<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)
{
}
#include "car.cpp"

This is wrong.这是错误的。 Never include source files.永远不要包含源文件。

 'Car' does not name a type

Why it happened为什么会发生

car.cpp attempts to use the class Car which has not been defined. car.cpp 尝试使用尚未定义的类Car

how to fix it?如何解决?

Add #include "car.h" into car.cpp to define Car before its use.#include "car.h"添加到 car.cpp 以在使用前定义Car Then remove #include "car.cpp" from car.h to avoid recursive inclusion that would prevent correct order of inclusion.然后从 car.h 中删除#include "car.cpp"以避免递归包含,这会阻止正确的包含顺序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM