模板运算符重载没有类,用于复数加法和乘法。 [英] Template operator overloading without class for complex number addition and multiplication.
问题描述
任何人都可以帮我写一个代码模板运算符重载没有类复杂的数字加法和乘法主要的主题是我不应该使用类,我可以使用结构,我应该使用模板来添加并乘以两个复数,我试图在互联网上搜索,但我没有找到一个。
Can anyone help me to write a code for "template operator overloading without class for complex number addition and multiplication"the main theme is i should not use "class" and i can use structure and i should use "template" to add and multiply for two complex number, i tried to search in internet but i did not found one.
1.here is my code:
template <typename complex_t> // template inz.
// struct
struct complex
{
complex Max(complex_t real_v, complex_t imag_v)
{
// i'm not sure what i have to declare inside this function
return 0;
}//template
complex()//default value
{
int real=0;
int imag=0;
}
};
complex operator + complex (Max(a,b))
{
complex c;
c.real=a.real+b.real;
c.imag=a.imag+b.imag;
return(c);
}
complex operator ++ max(complex& c3) // postfix increment
{
c3.real = c3.real + 1;
c3.imag = c3.imag + 1;
return c3;
}
//main
void main()
{
complex c1(1,-2),c2(2.3,19),c3;
c3=c1+c2;
c1++;
}
我的尝试:
i试图在互联网上搜索,但我没有得到任何明确的答案,甚至我试图编写代码,但它不起作用。
What I have tried:
i have tried to search in internet but i did not get any clear answer and even i tried to write code but it's not working.
推荐答案
为什么你需要模板来完成这样的任务吗?
你能告诉我们你的'不工作代码'吗?
这里有一个全球的例子(没有类)运算符重载:如何在C ++中全局重载opAssign运算符 - 堆栈溢出 [ ^ ]。
[更新]
我举个例子
Why do you need templates for such a task?
Could you please show us your 'not working code'?
Here an example of global (without class) operator overloading: How to overload opAssign operator globally in C++ - Stack Overflow[^].
[update]
I give you an example
#include <iostream>
using namespace std;
template <typename complex_t>
struct complex
{
complex_t real, imag;
complex( complex_t r, complex_t i):real(r), imag(i){}
complex():real(complex_t()), imag(complex_t()){}
};
template <typename complex_t >
complex<complex_t> operator + ( const complex<complex_t> & a, const complex<complex_t> & b)
{
complex<complex_t> c;
c.real = a.real + b.real;
c.imag = a.imag + b.imag;
return(c);
}
int main()
{
complex <double> c1(1,-2);
complex <double> c2(2.3,19);
complex <double> c3 = c1 + c2;
cout << "c3.real = " << c3.real << ", c3.imag = " << c3.imag << endl;
}
注意,因为 C ++ 11
,你可以写
Note, since C++11
, you might write
template <typename complex_t>
struct complex
{
complex_t real{}, imag{};
complex( complex_t r, complex_t i):real(r), imag(i){}
complex(){}
};
代替。
[/ update]
这篇关于模板运算符重载没有类,用于复数加法和乘法。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!