Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4568510
  • 博文数量: 385
  • 博客积分: 21208
  • 博客等级: 上将
  • 技术积分: 4393
  • 用 户 组: 普通用户
  • 注册时间: 2006-09-30 13:40
文章分类

全部博文(385)

文章存档

2015年(1)

2014年(3)

2012年(16)

2011年(42)

2010年(1)

2009年(2)

2008年(34)

2007年(188)

2006年(110)

分类: C/C++

2006-10-12 14:02:42


C++规定:运算符中,参数说明都是内部类型时,不能重载。
for example:
 int *operator  + (int ,int *);
 
即不允许进行下述运算
int  a=5;
int *pa=&a;
pa = a*pa;        //error
 
书上写的 
 . 
::
*
->
?:
这五个运算符不能重载。  但我在殷人昆的数据结构38页看到了可以重载,就试验了一下
 
 




#include <iostream>
using namespace std;


class Student
{
    public:
        Student (char *pName="no name",int ssId=0);
        Student (Student &s);
        char * operator *()
        {
                return name;
        }
        ~Student ();
        
    protected :
        char name[40];
        int id;

};

 Student:: Student (char *pName,int ssId)
{
            id=ssId;
            strcpy(name,pName);
            cout<<"Constructing new student"<<pName<<endl;
}
 Student::Student (Student &s)
 {
     cout <<"Constructing copy of "<<s.name<<endl;
     strcpy(name,"copy of ");
     strcat(name, s.name);
     id=s.id;
 
 }

 Student::~Student ()
{
   cout <<"Destructing "<<name<<endl;
}

void fn(Student s)
{
    cout<<"In function fn()\n";

}

int main()
{
    Student randy("Randy",1234);
    cout<<"Calling fn()\n";
    fn(randy);
    cout<<"Returned from fn()\n";
    
    
    printf("\nabc :%s\n",*randy);  //重载*
}

 

运算符重载函数的使用主要分为两种形式,一种是作为类的友元函数进行使用另一种则是作为类的成员函数进行使用
C++规定:

=

()

[]

->

这四种运算符必须为成员形式。

阅读(2387) | 评论(0) | 转发(0) |
0

上一篇:虚函数的限制

下一篇:增量运算符的重载

给主人留下些什么吧!~~