【问题标题】:C++ "undefined reference to" errorC++“未定义的引用”错误
【发布时间】:2013-05-06 22:39:10
【问题描述】:

首先不要惊慌。这是一个非常简单的程序。 使用“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() {

}

【问题讨论】:

标签: c++ file compilation header


【解决方案1】:

您缺少IVehicle 构造函数的定义。

【讨论】:

    【解决方案2】:

    乍一看我觉得IVehicle.h需要在Car.h中引用

    #include "IVehicle.h"

    【讨论】:

      【解决方案3】:

      这与您提出的问题不同,但您可能需要为后者注意,请参阅您的代码:

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

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

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

      【讨论】:

      • 或者至少输入this-&gt;name = name
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多