gpt4 book ai didi

c++ - c++中的成员模板函数有什么用?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:03:21 27 4
gpt4 key购买 nike

给定一个带有成员模板函数的类:

template <typename t>
class complex
{
public:
complex(t r, t im);
template<typename u>
complex(const complex<u>&);
private:
//what would be the type of real and imaginary data members here.
}

我对成员模板函数感到困惑,请提供一个示例,让我清楚地了解成员模板函数的需求。
还有,说说c++中成员模板函数的使用,我们在什么情况下使用成员模板函数?

最佳答案

它使您能够进行转换:

complex<int> ci;

complex<float> cf(ci);

因此,如果您有两种类型 T1 和 T2,并且您可以将 T1 分配给 T2,则可以分配 complex<T1>。到 complex<T2> .

至于你代码中的问题(这里的实数和虚数数据成员的类型是什么):

template <typename t>
class complex
{
...
private:
t real_part;
t imaginary_part;
};

关于c++ - c++中的成员模板函数有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2336454/

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