【问题标题】:Compiler error when dynamically allocating a template class where type is another object of template type动态分配类型是模板类型的另一个对象的模板类时出现编译器错误
【发布时间】:2013-04-02 17:40:55
【问题描述】:

这是我目前遇到的编译器错误

错误 C2679:二进制“=”:未找到采用“Pair”类型右侧操作数的运算符(或没有可接受的转换)

using namespace std;

template<typename T, typename U>
Array< Pair<T, U>>* zip(Array<T> & lhs,Array<U> & rhs) 
{
    int zipLen = (lhs.getLength() < rhs.getLength() ? lhs.getLength() : rhs.getLength());

    Array<Pair<T, U>>* zipped= new Array<Pair<T,U>>(zipLen);

    for (int i=0; i<zipLen; i++)
        zipped[i] = Pair<T, U>(lhs[i], rhs[i]);//and this is the line giving me problems

    return zipped;
}

int main()
{
    Array<int> a1(5);
    Array<char>a2(3);

    Array<Pair<int,char>>*a3;

    for(int i =1;i<5;i++)
        a1[i-1]=i;

    for(char ch='a';ch<='c';ch++)
        a2[ch-'a']=ch;

    a3=zip(a1,a2);

    cout<<a3;

    system("pause");
    return 0;
}

【问题讨论】:

  • 善用模板——扔掉这个system电话!

标签: c++ templates


【解决方案1】:

我相信您已将“zipped”声明为指向对数组的指针。因此,要访问数组的元素,您必须首先取消引用指针:

(*zipped)[i] = Pair<T, U>(lhs[i], rhs[i]);

【讨论】:

  • 谢谢 Sam,我按照你的方法试了一下,效果非常好,谢谢你的意见
  • 打印时还需要取消引用 a3。
猜你喜欢
  • 2010-12-31
  • 1970-01-01
  • 2013-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多