【问题标题】:templates and use class object function to compute模板并使用类对象函数计算
【发布时间】:2013-05-22 12:25:58
【问题描述】:

我有对象总线和汽车的两个向量。我需要创建一个模板来减去使用模板行驶的距离。距离减去只会在相同的对象内完成,如 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;
}

bus.h

class bus{

private:
int dist;

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

汽车.h

class car {

private:
int dist;

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

【问题讨论】:

  • 发布代码通常比谈论它的作用更好。如果我们看到类的定义,您的问题会更容易理解。
  • Appart 从语法错误(缺少}),从你给我们的信息看你的函数template&lt;class T&gt; double dist_difference(T x, T y); 似乎没问题。
  • 不,模板正是我想要的。问题是我什至无法将我的方法放入模板中,例如 x.getDist 不可行。这就是为什么我想知道如何在模板中使用类方法。我想我错过了一些东西,比如将类链接到模板以允许我使用它的功能
  • ...@hmjd 也指出,如果您打算将 cars 与 buses 进行比较,xy 的类型必须不同。
  • 不,我只需要在同一个对象内比较,汽车与汽车和巴士与巴士距离。

标签: c++ templates object vector


【解决方案1】:

你快到了:

汽车.h

struct Car {
  int dist;
};

dist.h

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

main.cpp

#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 的任何类型。当您使用该函数时,编译器会确保它,因为对于每个不同的类型T,它都会派生出它的一个专用版本。

【讨论】:

  • 哦,谢谢!所以你可以使用该函数并运行它...因为当我执行“x”时程序从不显示任何内容时它似乎不合逻辑。我虽然这肯定是一个错误...愚蠢的我..
  • 自动完成不起作用,因为在编译之前您不知道T 将采用哪种形式。您可以将T 视为在整个项目中提供给模板函数的所有类型的参数之间共享的公共接口。
猜你喜欢
  • 2013-09-23
  • 2023-04-07
  • 1970-01-01
  • 1970-01-01
  • 2018-11-24
  • 2011-11-30
  • 2014-02-11
  • 1970-01-01
  • 2019-04-18
相关资源
最近更新 更多