运算符重载的概念是什么 [英] what is the concept of operator overloading

查看:185
本文介绍了运算符重载的概念是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经用TC编译器编写了一个程序..并出现错误,但无法理解

I have written a program in TC compiler..and getting an error but could not understand

#include<iostream.h>
#include<conio.h>
class aman
{
	int real;
	int imag;
	public : aman(int a,int b)
		{
			real=a;
			imag=b;
		}
	       void showdata()
		{
			cout<<real<<"+i"<<imag<<endl;
		}
		 aman operator+(aman);
};
       aman aman::operator + (aman c)
	      {

		aman temp;

		temp.real=real+ c.real;
		temp.imag=imag+ c.imag;
		return (temp);
	      }
void main()
{
	clrscr();
	aman d,e,f;
       d=aman (5,6);
       e= aman (6,9);
	f=d+e;
	d.showdata();
	cout<<"a is";
	e.showdata();
	cout<<"b is";
	f.showdata();

	cout<<"f=d+e is:"<<endl;
	f.showdata();
	getch();
}





Error: could not find match for ‘aman::aman()’


它指向


and it is pointing on

aman aman::operator + (aman c)
	      {

		aman temp;
		temp.real=real+ c.real;
		temp.imag=imag+ c.imag;
		return (temp);
	      }


在此先感谢


Thanks in advance

推荐答案

一旦提供了参数化的构造函数,编译器将不会为您提供默认的普通构造函数.您需要手动定义普通ctor.

aman :: aman()
{
}
Once you provide a parameterized constructor, the compiler doesnt provide you the default plain one. You need to define your plain ctor manually.

aman::aman()
{
}


您还应该通过引用或指针将其传递给+运算符函数.
默认值是按值传递,这就是这里发生的情况.这将创建变量的完整副本,然后使用该副本调用函数,然后删除该副本.通过引用传递和通过指针传递只是传递内存地址的副本.这更快,特别是对于包含大量数据的类

You should also be passing by reference or pointer into the + operator function.
Pass by value is the default, and is what is happening here. This creates a full copy of the variable, then calls the function with this copy, then deletes the copy. Pass by reference and pass by pointer just pass a copy of the memory address. This is quicker, especially for classes which hold lots of data

class aman {
	//other functions here
	aman operator +(const aman&);
};

aman aman::operator +(const aman &c) {
	aman temp;
	temp.real = real + c.real;
	temp.imag = imag + c.imag;
	return (temp);
}


这篇关于运算符重载的概念是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆