程序忽略 .cpp 文件并拒绝确认 Ship.cpp 文件。一直说 "this file does not belong to any project target"

Program is ignoring .cpp file and refuses to acknowledge Ship.cpp file. Keeps saying "this file does not belong to any project target"

我的问题是出于某种原因 main.cpp 拒绝承认 Ship.cpp 存在。如果我添加 main.cpp #include "Ship.cpp",代码可以正常工作。可能是什么问题呢? (IDE 是 CLion)。以前从未发生过。

当我打开 ship.cpp 时,在顶部显示“此文件不属于任何项目目标”。

有没有人遇到过这样的问题,解决方法是什么?

SHIP.CPP:

#include <iostream>
#include "Ship.h"

std::string Ship::GetName() {
    return this->name;
}

int Ship::GetStorage() {
    return this->storage;
}

void Ship::SetName(std::string name) { this->name = name; }

void Ship::SetStorage(int storage) { this->storage = storage; }

void Ship::setAll(std::string name, int storage) {
    this->name = name;
    this->storage = storage;
}

Ship::Ship(std::string name, int storage) {
    this->name = name;
    this->storage = storage;
}

Ship::Ship() {
    this->name = "Stock Ship";
    this->storage = 10;
}

void Ship::toString() {
    std::cout << "This ship is called " <<
              this->name << " and has the storage capacity of " <<
              this->storage << " units.";
}

Ship.h:

    #ifndef UOSTASGAME_SHIP_H
#define UOSTASGAME_SHIP_H

#include <string>

class Ship {

private:


    std::string name;
    int storage;

public:

    Ship();
    Ship(std::string, int);

    std::string GetName();
    void SetName(std::string name);

    int GetStorage();
    void SetStorage(int storage);

    void setAll(std::string, int);

    void toString();

};


#endif //UOSTASGAME_SHIP_H

Main.cpp:

    #include <iostream>
#include "Ship.h"
int main() {

    Ship ship("Becky",10);
    Ship a;

    ship.toString();
    a.toString();



    return 0;
}

CLion 使用 CMake 来组织和构建您的项目,您的项目文件之一应该是 CMakeLists.txt,并且在其中,应该有一行看起来像

add_executable(target_name Main.cpp)

您需要将 Ship.cpp 文件添加到那里的来源

add_executable(target_name Main.cpp Ship.cpp)

作为旁注,您可能通过控制台或文件资源管理器手动添加了 Ship.cpp 文件,如果您通过 IDE 添加它,方法是右键单击左侧的项目根目录面板并选择添加新 class,CLion 会自动将源添加到 CMakeLists.txt。