给定一个带有成员模板函数的类:
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/