首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

关于这个程序的几个小问题

2012-03-28 
关于这个程序的几个问题C/C++ code// UnaryOperator.cpp -- 一元运算符重载#include iostream#include

关于这个程序的几个问题

C/C++ code
// UnaryOperator.cpp -- 一元运算符重载#include <iostream>#include <string>using namespace std;class Integer{    long i;    Integer *This()    {        return this;    }public:    Integer(long n = 56):i(n){}    friend const Integer &operator +(const Integer &a); //为什么最后一行有&而其他的没有,返回引用的意思吗?    friend const Integer operator -(const Integer &a);    friend const Integer operator ~(const Integer &a);    friend Integer *operator &(Integer &a);};const Integer &operator +(const Integer &a){    cout <<" + Integer\n" <<a.i;    return a;}const Integer operator -(const Integer &a){    cout <<" - Integer\n" <<a.i;    return  Integer(-a.i);}const Integer operator ~(const Integer &a){    cout <<" ~ Integer\n" <<a.i;    return Integer(~a.i);}Integer *operator &(Integer &a){    cout <<" & Integer\n" <<a.i;    return a.This();}void f(Integer a){    +a;    -a;    ~a;    Integer *ip = &a;}int main(){    Integer a;    f(a);    return 0;}




以上注释的那一段,到底和别的未加&的有什么区别?还有这个友元的声明是必须的吗??

[解决办法]
最后一行是重载的&操作符啊 
友元的话,因为那几个方法并不是类的成员,而long i是私有(默认)成员,所以要访问i是必须的。

还有,这个程序没有包括的部分才是最麻烦的:重载构造函数,重载new和delete ,重载=。这些就很纠结了
当然还有重载逻辑运算符
[解决办法]
你需要弄明白operator的用法:
1.1operator overloading
C++可能通过operator 重载操作符,格式如下:类型T operator 操作符 (),如比重载+,如下所示
template<typename T> class A
{
public:
const T operator + (const T& rhs)
{
return this->m_ + rhs;
}
private:
T m_;
};

又比如STL中的函数对象,重载(),如下所示
template<typename T> struct A
{
T operator()(const T& lhs, const T& rhs){ return lhs-rhs;}
};


1.2 operator casting
C++可能通过operator 重载隐式转换,格式如下: operator 类型T (),如下所示
class A
{
public:
operator B* () { return this->b_;} 
operator const B* () {return this->b_;}
operator B& () {return *this->b_;}
private:
B* b_;
};
A a;
当if(a),编译时,其中它转换成if(a.operator B*()),其实也就是判断 if(a.b_)
2.关于 friend 用法 为了访问本类的private 成员 
 主要表现为 一个类或一个方法需要使用类里面的private成员!
不知道明白没!


[解决办法]
不要轻易的重载&
[解决办法]
& && ||这三个操作符,不到万不得已的情况下,千万不要重载
[解决办法]
你重载的不是加的操作符,而是正号的操作符重载,加的操作符重载,如果不是类的成员函数,那么参数必须是2个参数,而你的只有一个参数,所以返回类型才是引用,
如果重载的是加操作符,是不返会引用的

热点排行