朱倩倩zqq 2021-05-16 22:34 采纳率: 75%
浏览 20
已采纳

关于类模板问题(求大佬解决)

#include<iostream>
using namespace std;
template <class T = int, class S = int>
class Pair {
public:

    Pair() { }
    Pair(T _first, S _second) : first(_first), second(_second) { }
    void print();

private:
    T first;
    S second;

};
template<class T,class S>
void pair<T, S>::print()//问题1.为什么此处显示上面没有成员print.函数。
{

}

template <class T>

 pair<int,int> search( T* vec, int n, const T &data)//问题2;它不是template<class T,class S>而且pair<int ,int>是什么意思呢?是表示它是属于pair<int,int>类的一个函数,可是函数里也没有声明?

{

pair<int, int>a;

vec = new T[n];

cout << "给数组元素赋值:" << endl;

for (int i = 0; i < n; i++)

cin >>vec[i];

int count = 0;

for (int i = 0; i < n; i++)

{

if (data==vec[i])

{

count++;

if (count==1)

{

a.first = i;

}

else if (count >= 2)

{

a.second = i;

}

}

else if(data!=vec[i])

vec[i] = -1;

 

}

  

cout << "第一次出现的位置为:" << a.first << endl;

if (a.second == a.first)

cout << "最后一次出现的位置和first一样也是:" << a.second << endl;

else

cout << "最后一次出现的位置为:" << a.second << endl;

return a;

}

int main()
{
    

}

  • 写回答

2条回答 默认 最新

  • benbenli 2021-05-16 22:43
    关注

    你的代码里的小写pair要改成你自己定义的大写P开头的Pair,编译就没问题了。否则编译器以为是std::pair了。如下。

     

     

    #include<iostream>
    using namespace std;
    template <class T = int, class S = int>
    class Pair {
    public:

        Pair() { }
        Pair(T _first, S _second) : first(_first), second(_second) { }
        void print();

    private:
        T first;
        S second;

    };
    template<class T,class S>
    void Pair<T, S>::print()//问题1.为什么此处显示上面没有成员print.函数。
    {
    }

    template <class T>

     Pair<int,int> search( T* vec, int n, const T &data)//问题2;它不是template<class T,class S>而且pair<int ,int>是什么意思呢?是表示它是属于pair<int,int>类的一个函数,可是函数里也没有声明?

    {
    Pair<int, int>a;

    vec = new T[n];

    cout << "给数组元素赋值:" << endl;

    for (int i = 0; i < n; i++)

    cin >>vec[i];

    int count = 0;

    for (int i = 0; i < n; i++)

    {
    if (data==vec[i])

    {
    count++;

    if (count==1)

    {
    a.first = i;

    }

    else if (count >= 2)

    {
    a.second = i;

    }

    }

    else if(data!=vec[i])

    vec[i] = -1;

     

    }

      

    cout << "第一次出现的位置为:" << a.first << endl;

    if (a.second == a.first)

    cout << "最后一次出现的位置和first一样也是:" << a.second << endl;

    else

    cout << "最后一次出现的位置为:" << a.second << endl;

    return a;

    }

    int main()
    {
        

    }

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 matlab用simulink求解一个二阶微分方程,要求截图
  • ¥30 matlab解优化问题代码
  • ¥15 写论文,需要数据支撑
  • ¥15 identifier of an instance of 类 was altered from xx to xx错误
  • ¥100 反编译微信小游戏求指导
  • ¥15 docker模式webrtc-streamer 无法播放公网rtsp
  • ¥15 学不会递归,理解不了汉诺塔参数变化
  • ¥15 基于图神经网络的COVID-19药物筛选研究
  • ¥30 软件自定义无线电该怎样使用
  • ¥15 R语言mediation包做中介分析,直接效应和间接效应都很小,为什么?