我对隐式和显式声明感到困惑。我不知道为什么你需要在某些时候明确地说或。例如,
在我的 main.cpp 中
#include <iostream>
#include "Point.h"
int main()
{
Point<int> i(5, 4);
Point<double> *j = new Point<double> (5.2, 3.3);
std::cout << i << *j;
Point<int> k;
std::cin >> k;
std::cout << k;
}
Point<int> k
.为什么我必须使用显式声明?否则我会收到编译错误。还是我在 Point.h 文件中的编码不正确?
点.h:
#ifndef POINT_H
#define POINT_H
#include <iostream>
template <class T>
class Point
{
public:
Point();
Point(T xCoordinate, T yCoordinate);
template <class G>
friend std::ostream &operator<<(std::ostream &out, const Point<G> &aPoint);
template <class G>
friend std::istream &operator>>(std::istream &in, const Point<G> &aPoint);
private:
T xCoordinate;
T yCoordinate;
};
template <class T>
Point<T>::Point() : xCoordinate(0), yCoordinate(0)
{}
template <class T>
Point<T>::Point(T xCoordinate, T yCoordinate) : xCoordinate(xCoordinate), yCoordinate(yCoordinate)
{}
template <class G>
std::ostream &operator<<(std::ostream &out, const Point<G> &aPoint)
{
std::cout << "(" << aPoint.xCoordinate << ", " << aPoint.yCoordinate << ")";
return out;
}
template <class G>
std::istream &operator>>(std::istream &in, const Point<G> &aPoint)
{
int x, y;
std::cout << "Enter x coordinate: ";
in >> x;
std::cout << "Enter y coordinate: ";
in >> y;
Point<G>(x, y);
return in;
}
#endif
最佳答案
对于类模板,必须显式指定模板参数。
对于函数模板,可以隐式推断模板参数。
Point
是一个类,因此需要显式声明。
关于c++ - 与隐式和显式模板声明混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2970253/