重载成员访问操作符
❶ 关于C++重载运算符
关于C++重载运算符,请看以下的专题:
http://bbs.data10000.com/bbs/forumdisplay.php?fid=5
❷ 操作符的重载方法
//使用成员函数重载运算符
#include <iostream>
using namespace std;
class example
{
private:
int val;
public:
example(int v = 0) { val = v; }
void setval(int v) { val = v; }
int getval() { return val; }
example operator +(example);
};
//成员函数重载运算符只需要一个参数,执行时由表达式左边的对象调用函数
example example::operator +(example o)
{
example t(val + o.val);
return t;
}
int main()
{
example ex1(3), ex2, ex3;
ex2.setval(5);
ex3 = ex1 + ex2; //由ex1调用函数
cout << ex3.getval() << endl;
return 0;
}
//使用友元函数重载运算符,主函数同上
class example
{
private:
int val;
public:
example(int v = 0) { val = v; }
void setval(int v) { val = v; }
int getval() { return val; }
friend example operator +(example, example);
};
//友元函数重载运算符需要两个参数,可以直接访问类的私有数据成员
example operator +(example o1, example o2)
{
example t(o1.val + o2.val);
return t;
}
//使用普通函数重载运算符,主函数同上
class example
{
private:
int val;
public:
example(int v = 0) { val = v; }
void setval(int v) { val = v; }
int getval() { return val; }
};
//普通函数重载运算符需要两个参数,不能直接访问类的私有数据成员
example operator +(example o1, example o2)
{
example t(o1.getval() + o2.getval());
return t;
}
❸ 关于C++操作符重载问题
&在这里是返回一个引用的意思
这个函数其实就是返回一个CSstring的类的引用
传递的参数中的&也一样
因为返回引用比返回对象效率更好 传递参数也是同理
所以很多时候都要用到&
❹ c++重载类成员函数操作符
"无法通过"是什么?请贴出出错信息。
❺ c++重载运算符
#include<iostream>
#include<cmath>
usingnamespacestd;
classPoint
{
public:
Point(doublexx,doubleyy)
{
x=xx;
y=yy;
};
voidGetxy();
frienddoubleDistance(Point&a,Point&b);
private:
doublex,y;
};
voidPoint::Getxy()
{
cout<<"("<<x<<","<<y<<")"<<endl;
}
doubleDistance(Point&a,Point&b)
{
doubledx=a.x-b.x;
doubledy=a.y-b.y;
returnsqrt(dx*dx+dy*dy);
}
intmain(void)
{
Pointp1(3.0,4.0),p2(6.0,8.0);
p1.Getxy();
p2.Getxy();
doubled=Distance(p1,p2);
cout<<"Distanceis"<<d<<endl;
return0;
}
是不是字符串操作有问题?
❻ C++中成员访问操作符重载是怎么回事
这两个操作符在实现智能指针的时候需要重载,是为了访问真正的指针,其它时候很少有用到这两个符号重载的。
❼ C++重载操作符的问题
重载时面向对象的思想,而结构体是C语言遗留下来的,用C++编程,完全可以用类来代替结构体。如果你学C++还经常用C语言的思想,你很难学好面向对象的思想。
你说的问题,只需要重载“-”就可以了。
示例代码如下:
#include
<iostream.h>
//为了方便,我就把类和主函数写在一起
class
Object
//定义类
{
private:
//私有变量
int
x;
public:
//公有
void
Set(int
value)
//设置值
{
x=value;
}
int
Get()
//获取值
{
return
x;
}
Object
operator
-
(Object
&o)
//重载-号
{
Object
o2;
o2.x=this->x;
//获取当前值
o2.x=o2.x-o.x;
//减法运算
return
o2;
}
};
void
main()
{
Object
a,b;
a.Set(6);
b.Set(20);
cout<<"改变前:"<<endl;
cout<<"a:
x="<<a.Get()<<endl;
cout<<"b:
x="<<b.Get()<<endl;
b=b-a;
cout<<"改变后:"<<endl;
cout<<"b:
x="<<b.Get()<<endl;
}