我对隐式声明和显式声明感到困惑.我不知道为什么你需要明确说出或在某些时候.例如,
在我的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;
}
Run Code Online (Sandbox Code Playgroud)
对Point<int> k.为什么我必须使用显式声明?否则我会收到编译错误.或者我的Point.h文件中的编码不正确?
Point.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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
726 次 |
| 最近记录: |