如何正确实例化(has-a)类?未定义的符号?

时间:2015-05-07 09:15:50

标签: c++ xcode

所以我是C ++的新手,我主要是从一本书中读书,但过了一段时间后我意识到它很模糊。目前只是通过一些例子来了解我的一些知识,但我现在正在解决这个问题,我已经尝试回顾我的步骤并从头开始两次,并最终得到同样的问题。

问题:我有一个车辆类,有一个Engine和一个Tank,但在编译时我得到一个未定义符号的错误。

Xcode错误:

Undefined symbols for architecture x86_64:   "Tank::Tank(float)", referenced from:
      Vehicle::Vehicle(int, float, int) in Vehicle.o   "Tank::~Tank()", referenced from:
      Vehicle::Vehicle(int, float, int) in Vehicle.o   "Engine::Engine(int)", referenced from:
      Vehicle::Vehicle(int, float, int) in Vehicle.o   "Engine::~Engine()", referenced from:
      Vehicle::Vehicle(int, float, int) in Vehicle.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation)

举例:建造汽车

文件夹结构:

Tank/
  Tank.h
  Tank.cpp
Engine/
  Engine.h
  Engine.cpp
Vehicle.h
vehicle.cpp
main.cpp

Tank.h

#ifndef __Test__Tank__
#define __Test__Tank__
class Tank
{
public:
    Tank (float);
    virtual ~Tank();


protected:
    const float tankCapacity;

};
#endif

Tank.cpp

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

using namespace std;

//Implementation of constructor
Tank::Tank(float capacity) : tankCapacity(capacity){
    cout << "Tank was created...with a tank capacity of " <<  this->getTankCapacity()<< endl;
}
//Implementation of destructor
Tank::~Tank(){
    cout << "Tank was destroyed..." << endl;
}

Engine.h

#ifndef __Test__Engine__
#define __Test__Engine__

#include <iostream>
#include "../Tank/Tank.h"
class Engine
{
public:
    Engine(int);
    ~Engine();

protected:
    bool started;
    int trip, numCyl;

};


#endif /* defined(__Test__Engine__) */

Engine.cpp

#include <iostream>
#include "Engine.h"
using namespace std;

Engine::Engine(int num) : numCyl(num)
{
    this->started = false;
    this->trip = 0;
    cout << "Engine was created with " << this->numCyl << " cylinders" << endl;
}

Engine::~Engine(){
    cout << "Engine was destroyed" << endl;
}

Vehicle.h

#ifndef __Test__Vehicle__
#define __Test__Vehicle__

#include <iostream>
#include "Engine/Engine.h"
#include "Tank/Tank.h"

class Vehicle
{
public:
    ~Vehicle();

protected:
    Vehicle(int occ, float tankCapacity, int numCyl);
    int occupants;
    Engine engine;
    Tank tank;
private:
    Vehicle();


};


#endif /* defined(__Test__Vehicle__) */

Vehicle.cpp

#include <iostream>
#include "Tank/Tank.h"
#include "Engine/Engine.h"
#include "Vehicle.h"


using namespace std;

Vehicle::Vehicle(int occ, float tankCapacity, int numCyl) : engine(numCyl), tank(tankCapacity)
{
    this->occupants = occ;
    cout << "Vehicle Created" << endl;
}

感谢您提供的任何帮助,我们将不胜感激任何小提示!

0 个答案:

没有答案