gpt4 book ai didi

c++ - operator<<(ostream&, const BigUnsigned&) 必须只有一个参数

转载 作者:太空狗 更新时间:2023-10-29 23:32:35 25 4
gpt4 key购买 nike

我试图将模板化类的模板化成员函数的声明和定义分开,但最终出现以下错误和警告。

template <typename I>
class BigUnsigned{
const size_t cell_size=sizeof(I);
std::vector<I> _integers;
public:
BigUnsigned();
BigUnsigned(I);
friend std::ostream& operator<<(std::ostream& out, const BigUnsigned& bu);
};

std::ostream& operator<<(std::ostream& out, const BigUnsigned& bu){
for (auto integer : bu._integers){
out<<integer<<std::endl;
}
return out;
}

../hw06/bigunsigned.h:13:77: warning: friend declaration 'std::ostream& operator<<(std::ostream&, const BigUnsigned&)' declares a non-template function [-Wnon-template-friend] friend std::ostream& operator<<(std::ostream& out, const BigUnsigned& bu); ^ ../hw06/bigunsigned.h:13:77: note: (if this is not what you intended, make sure the function template has already been declared and add <> after the function name here) ../hw06/bigunsigned.h:16:51: error: invalid use of template-name 'BigUnsigned' without an argument list std::ostream& operator<<(std::ostream& out, const BigUnsigned& bu){ ^ ../hw06/bigunsigned.h: In function 'std::ostream& operator<<(std::ostream&, const int&)': ../hw06/bigunsigned.h:17:28: error: request for member '_integers' in 'bu', which is of non-class type 'const int' for (auto integer : bu._integers){ ^

当我像这样加入声明和定义时,一切都可以正常编译。

template <typename I>
class BigUnsigned{
const size_t cell_size=sizeof(I);
std::vector<I> _integers;
public:
BigUnsigned();
BigUnsigned(I);
friend std::ostream& operator<<(std::ostream& out, const BigUnsigned& bu){
for (auto integer : bu._integers){
out<<integer<<std::endl;
}
return out;
}
};

目的是打印成员变量_integers到cout。可能是什么问题?

附言:使用 this question我免费提供了该功能,但没有帮助。

最佳答案

BigUnsigned是模板类型所以

std::ostream& operator<<(std::ostream& out, const BigUnsigned& bu)

将无法工作,因为没有 BigUnsigned .您需要将 friend 函数设为模板,以便您可以采用不同类型的 BigUnsigned<some_type>

template <typename I>
class BigUnsigned{
const size_t cell_size=sizeof(I);
std::vector<I> _integers;
public:
BigUnsigned();
BigUnsigned(I);
template<typename T>
friend std::ostream& operator<<(std::ostream& out, const BigUnsigned<T>& bu);
};

template<typename T>
std::ostream& operator<<(std::ostream& out, const BigUnsigned<T>& bu){
for (auto integer : bu._integers){
out<<integer<<std::endl;
}
return out;
}

第二个示例之所以有效,是因为它是在类内部声明的,所以它使用了该类使用的模板类型。

关于c++ - operator<<(ostream&, const BigUnsigned<I>&) 必须只有一个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34928076/

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