重載成員訪問操作符
❶ 關於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;
}
