我是 C++ 新手,正在努力完成 C++ 作业。在代码问题中,我无法更改主函数中的任何内容,但可以在主函数之外添加代码。
这是主要的:
int main()
{
MySet<int> stInt;
int a[100];
int n;
cin >> n;
for(int i = 0;i < n; ++i )
cin >> a[i];
MySet<int> stInt(a,a+n);
MyPrint(stInt.begin(),stInt.end());
cout << endl;
int s,e;
cin >> s >> e;
pair<MySet<int>::iterator, MySet<int>::iterator> p;
p = stInt.FindInterval(s,e);
if( p.first != p.second)
{
MyPrint(p.first,p.second);
cout << endl;
}
else
cout << "Interval Not Found" << endl;
cin >> n;
MySet<double,greater<double> > stDouble;
for( int i = 0;i < n; ++i)
{
double d;
cin >> d;
stDouble.insert(d);
}
MyPrint(stDouble.begin(),stDouble.end());
cout << endl;
double w;
cin >> w;
cout << * stDouble.upper_bound(w) << endl;
return 0;
}
为了得到正确的答案,我的想法是创建一个名为MySet
的新STL类,它继承自STL set,似乎是MyPrint()
函数有一些错误。我真的不知道这是什么。
顺便说一句,我在 VS2010 Pro 中编译代码。错误信息是:
未解析的外部符号“void __cdecl MyPrint(class std::_Tree_const_iterator,class std::allocator,0>> >,class std::_Tree_const_iterator,class std::allocator,0>> >)”(?MyPrint@ @YAXV?$_Tree_const_iterator@V?$_Tree_val@V?$_Tset_traits@NU?$less@N@std@@V?$allocator@N@2@$0A@@std@@@std@@@std@@ 0@Z) 在函数_main 中引用
我的代码片段是:
template<typename T, class Compare = less<T>, class Alloc = allocator<T> >
class MySet:public set<T>
{
private:
T st[100];
public:
MySet():set<T>() {}
MySet(int *first, int *last)
{
int *idx = first;
for(int i = 0; idx <= last; ++idx, ++i)
st[i] = *idx;
}
pair<typename set<T>::iterator, typename set<T>::iterator>FindInterval(int lower, int upper)
{
typename set<T>::iterator low, up;
low = lower_bound(lower);
up = upper_bound(upper);
return (pair<typename set<T>::iterator, typename set<T>::iterator>(low, up));
}
void friend MyPrint(typename set<T>::iterator first_, typename set<T>::iterator last_);
};
template<typename T>
void MyPrint(typename MySet<T>::iterator first_, typename MySet<T>::iterator last_)
{
typename MySet<T>::iterator it = first_;
for(; it != last_; ++it)
cout << *it << " ";
}
MyPrint()
函数只是打印 MySet
中的所有元素。
我已经问过所有了解 C++ 的人,但似乎他们无法帮助我......我被困了 3 天多......
谢谢!
忆如
最佳答案
您的程序声明了两个函数 - 或者更确切地说,两个函数族 - 名为 MyPrint
。首先,有一组非模板friend
函数,每个实例化一个MySet
模板。其次,有一组 MyPrint
模板的实例化。但是您只提供第二组的实际实现。
对于 main
中的 MyPrint
调用,两个集合都是可行的候选者,并且其他条件相同,编译器更喜欢非模板而不是模板。然后链接器发现非模板缺少实现。
有两种解决方法。您可以在类里面实现非模板,然后删除模板:
template <typename T>
class MySet {
friend void MyPrint(...) { ... }
};
或者您可以与模板成为 friend ,并删除非模板:
template <typename T>
void MyPrint(typename set<T>::iterator, typename set<T>::iterator);
template <typename T>
class MySet {
friend void MyPrint<T>(typename set<T>::iterator, typename set<T>::iterator);
};
template <typename T>
void MyPrint(typename set<T>::iterator, typename set<T>::iterator)
{ ... }
关于c++ - 创建从 STL 集继承的新类的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23419505/