gpt4 book ai didi

c++ - 带模板的友元函数

转载 作者:行者123 更新时间:2023-11-28 05:32:18 27 4
gpt4 key购买 nike

我有一个泛型类 Array1d,其友元函数声明为,

friend std::ostream& operator<< <>(std ::ostream& out, Array1D<T>& a);

定义为

template<typename U>
std::ostream& operator<< (std ::ostream& out, Array1D<U> a){
for(int i=0;i<a.size;i++){
out<<a[i]<<" ";
}
out<<endl;
return out;
}

但如果我尝试,

Array1D<int> a;
cout<<a;

我收到这个错误

(1).cpp|62|error: template-id 'operator<< <>' for 'std::ostream& operator<<(std::ostream&, Array1D<int>&)' does not match any template declaration|

我已尝试为 int 显式实例化它,

std::ostream& operator<< (std ::ostream& out, Array1D<int> a){
for(int i=0;i<a.size;i++){
out<<a[i]<<" ";
}
out<<endl;
return out;
}

但它给出了同样的错误。感谢帮助。

最佳答案

  1. friend std::ostream& operator<< <>(std ::ostream& out, Array1D<T>& a);
  2. template<typename U>
    std::ostream& operator<< (std ::ostream& out, Array1D<U> a)

这两个不是同一个函数。这是因为 Array1D<T>是具体类型。如果您希望 1. 与 2. 相匹配,您需要将其设为模板,可以将其设为 Array1D<U>。 .如果您想过于谨慎,不妨检查一下 T=U。

关于c++ - 带模板的友元函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39181864/

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