0

我有对象总线和汽车的两个向量。我需要创建一个模板来减去使用模板行驶的距离。距离减去只会在相同的对象内完成,如 bus1.dis - bus2.dis。

问题是我不允许使用重载运算符来编码这个模板,我需要使用公共汽车和汽车类的 getDistance(return dist) 方法来进行计算。我不知道怎么做!!!

任何人都知道如何使用类方法在模板上使用?我的模板和类对象在不同的​​标题上。我的模板需要接受任何对象并减去同一对象内的距离。

也许像 T getDistance() - T getDistance() ....

模板.h

template <class T>
double dist_difference(T x,T y) {
double distance = x.getDist() - y.getDist();
return distance;
}

衬套

class bus{

private:
int dist;

public:
int getDist();
void setDist(int);
};

汽车.h

class car {

private:
int dist;

public:
int getDist();
void setDist(int);
};
4

1 回答 1

0

你几乎在那里:

汽车.h

struct Car {
  int dist;
};

分布.h

template<class T>
int distDiff(T x, T y) {
  return x.dist - y.dist;
}

主文件

#include "car.h"
#include "dist.h"

#include <iostream>

int main(int argc, char* argv[]) {
  Car a;
  a.dist = 10;

  Car b;
  b.dist = 5;

  int dist = distDiff(a, b);
  std::cout << dist << std::endl;
}

输出:

5

类型T可以是定义属性的任何类型dist。当您使用该函数时,编译器会确保它,因为对于每种不同的 type T,它都会派生出它的专用版本。

于 2013-05-22T13:27:30.387 回答