gpt4 book ai didi

c++ - friend ,模板,重载<<

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:58:06 27 4
gpt4 key购买 nike

我正在尝试使用友元函数重载 << 和模板来熟悉模板。我不知道这些编译错误是什么:

Point.cpp:11: error:  shadows template parm 'class T'
Point.cpp:12: error: declaration of 'const Point<T>& T'

对于这个文件

#include "Point.h"

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 T>
std::ostream &operator<<(std::ostream &out, const Point<T> &T)
{
std::cout << "(" << T.xCoordinate << ", " << T.yCoordinate << ")";
return out;
}

我的标题看起来像:

#ifndef POINT_H
#define POINT_H

#include <iostream>

template <class T>
class Point
{
public:
Point();
Point(T xCoordinate, T yCoordinate);
friend std::ostream &operator<<(std::ostream &out, const Point<T> &T);

private:
T xCoordinate;
T yCoordinate;
};

#endif

我的标题也给出了警告:

Point.h:12: warning: friend declaration 'std::ostream& operator<<(std::ostream&, const Point<T>&)' declares a non-template function

我也不确定为什么。有什么想法吗?谢谢。

最佳答案

模板参数和函数参数同名。将其更改为:

template <class T>
std::ostream &operator<<(std::ostream &out, const Point<T> &point)
{
std::cout << "(" << point.xCoordinate << ", " << point.yCoordinate << ")";
return out;
}

标题中友元函数的声明也应该改变:

template <class G>
friend std::ostream &operator<<(std::ostream &out, const Point<G> &point);

关于c++ - friend ,模板,重载<<,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2963842/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com