gpt4 book ai didi

c++ - << 模板类对象的运算符重载

转载 作者:太空宇宙 更新时间:2023-11-03 10:28:16 25 4
gpt4 key购买 nike

我写了一个像bitset类的C++ STL:

template<size_t N>
class bitset {
public:
...........
friend std::ostream& operator << (std::ostream &, bitset<N> const&);
private:
..........
};
// end of class

template<size_t N>
std::ostream& operator << (std::ostream &os, bitset<N> const& rhs) {
............
.........
return os;
}

我正在尝试这样使用它:

bitset<5> foo; // success
std::cout << foo << std::endl; // fail

错误信息是——

undefined reference to `operator<<(std::ostream&, bitSet<5u> const&)

究竟是什么问题?

最佳答案

你 friend 的声明也必须是模板,就像定义一样:

template <size_t N>
class bitset {
public:
template <size_t M>
friend std::ostream& operator << (std::ostream &, bitset<M> const&);
};

template <size_t M>
std::ostream& operator << (std::ostream &os, bitset<M> const& rhs) {
return os;
}

或者,您可以声明 operator<<直接在类范围内:

template<size_t N>
class bitset {
public:
friend std::ostream& operator << (std::ostream & os, bitset const&) {
return os;
}
};

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

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