【发布时间】:2023-03-11 03:00:01
【问题描述】:
我想为我的向量类添加一个迭代器类类型,我将一些比较运算符声明为迭代器类的友元函数。但它没有正确编译,我做了前向声明。
template<class object>class vector;
template<class object>
bool operator<(typename vector<object>::const_iterator& lhs, typename vector<object>::const_iterator& rhs);
template<class object>class vector {
protected:
//some member
public:
class const_iterator {
friend bool operator< <>(const_iterator& lhs, const_iterator& rhs);
friend bool operator> <>(const_iterator& lhs, const_iterator& rhs);
//...
};
};
编译器说没有找到匹配的重载函数,我用的是vs2019。我猜前向声明有问题。
另一个问题是,我注意到有些人在类中声明友元函数时使用这种形式。
class myclass{
friend void foo<T>(T t);
//...
}
但是当声明一个操作符为友元时就不同了
friend bool operator< <>(const myclass& lhs, const myclass& rhs);
我想知道这两者有什么区别。
请帮帮我,非常感谢。
【问题讨论】:
-
请每个 stackoverflow.com 问题一个问题。
-
@Chipster - 抱歉,我有时会通过语言律师考试,可能不应该使用这个词。我可以像
my_func<int>(42)这样调用函数模板的实例。但是如果编译器可以从函数参数中推断出模板参数,我可以说my_func<>(42)。这就是那行正在做的事情,只是带有一个函数签名。 -
@parktomatomi 哦,知道了。我现在明白了。
-
@zxy1122 您提供的声明在 VS 2019 上对我来说在 VS 2019 上编译得很好。您能澄清一下您编写的触发错误的代码吗?