C++ "undefined reference to"错误

C++ "undefined reference to" error

本文关键字:错误 to undefined C++ reference      更新时间:2023-10-16

首先不要惊慌。这是一个非常简单的程序。我在用"g++ -Wall -pedantic Main.cpp"编译Main.cpp时得到这个错误这是我所有的文件。是什么导致未定义的引用出错?

Main.cpp

#include <iostream>
#include "BMWLogo.h"
#include "Engine.h"
#include "IVehicle.h"
#include "Car.h"
#include "BMW.h"
int main() {
    BMW* bmw = new BMW();
    Car* car = bmw;
    std::cout << car->getName() << std::endl;
}

IVehicle.h

class IVehicle {
    public:
        IVehicle();
        virtual std::string getName();
        virtual float getCurrentSpeed();
};

IVehicle.cpp

#include "IVehicle.h"
IVehicle::IVehicle() {
}
virtual std::string IVehicle::getName() {
}
virtual float IVehicle::getCurrentSpeed() {
}

Car.h

class Car : public IVehicle {
    private:
        std::string name;
        float currentSpeed;
        Engine* engine;
    public:
        Car(std::string name);
        void setCurrentSpeed(float currentSpeed);
        float getCurrentSpeed();
        std::string getName();
};

Car.cpp

#include "Car.h"
Car::Car(std::string name) {
    this->name = name;
    engine = new Engine();
}
void Car::setCurrentSpeed(float currentSpeed) {
    this->currentSpeed = currentSpeed;
}
float Car::getCurrentSpeed() {
    return currentSpeed;
}
std::string Car::getName() {
    return name;
}

BMW.h

class BMW : public Car {
    private: 
        BMWLogo* bmwLogo;
    public:
        BMW();
};

BMW.cpp

#include "BMW.h"
BMW::BMW()
: Car("BMW") {
    bmwLogo = new BMWLogo();
}

Engine.h

class Engine {
    Engine();
};

Engine.cpp

#include "Engine.h"
Engine::Engine() {
}

BMWLogo.h

class BMWLogo {
    BMWLogo();
};

BMWLogo.cpp

#include "BMWLogo.h"
BMLogo::BMWLogo() {
}

您错过了IVehicle构造函数的定义。

乍一看,我认为IVehicle.h需要在Car.h中引用

#include "IVehicle.h"

这是一个不同于你所问的问题,但你可能想要注意它后面,看你的代码:

Car::Car(std::string name) {
    name = name;
    engine = new Engine();
}

您可能希望更改参数名称,以便它不会隐藏name的类实例。试一试:

Car::Car(std::string p_name) {
    name = p_name;
    engine = new Engine();
}
相关文章: