gpt4 book ai didi

c++ - 使用模板...我的代码有什么问题?

转载 作者:行者123 更新时间:2023-11-28 06:26:29 24 4
gpt4 key购买 nike

我最近正在学习 C++ 中的模板。但是,即使我完全按照类(class)中的方式进行所有操作,我还是出现了 3 个错误。

这是ma​​in.cpp:

#include <iostream>
#include "szablony.h"

using namespace std;

int main()
{
cout << nmax<int>(55,402) << endl;

Klasa<double> a1;
a1.ustaw(25.54);

Klasa<double> a2;
a2.ustaw(44.55);

cout << a1.podaj() << " :max: " << a2.podaj() << " = " <<
nmax<Klasa>(a1.podaj(),a2.podaj()) << endl;

}

这是“szablony.h”:

#include <iostream>

using namespace std;

template <typename T> class Klasa
{
T wartosc;

public:

template <typename U> T podaj()
{
return (this -> wartosc);
}

template <typename U> void ustaw(U war)
{
wartosc=war;
}
};

template <typename T, typename T1, typename T2> T nmax(T1 n1, T2 n2)
{
return (n1 > n2 ? n1 : n2);
}

template <> Klasa nmax<Klasa>(Klasa n1, Klasa n2)
{
return (n1.podaj() > n2.podaj() ? n1 : n2);
}

所以这些是错误:

  1. “szablony.h”:|第 27 行|错误:在没有参数列表的情况下无效使用模板名称“Klasa”|

  2. main.cpp|第 16 行|错误:没有匹配函数来调用 'Klasa::podaj()'|

  3. main.cpp|第 17 行|错误:没有用于调用“Klasa::podaj()”的匹配函数|

顺便说一句,这门类(class)是从 2004 年开始的,这可能是一个原因,但即使我在互联网上查看,一切似乎都还不错......

提前谢谢你:)

最佳答案

主要问题是Klasa是一个模板类,但你在 nmax 的特化中使用它作为普通类(class)。特别是,Klasa不代表类型,但例如Klasa<int>

所以要么让你的函数返回一个模板模板,要么使用Klasa<type>

关于c++ - 使用模板...我的代码有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28443499/

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