December 30, 2004

关于C++操作赋值符重载

以前很少重载赋值操作符,今天由于程序需要,所以试了试,发现自己理解的并不是那么清楚。经过多次试验,现总结记录下来。

问题的发现

写一个简单的类,重载赋值操作符。然后在main函数中使用。简单的代码如下:

#include <iostream>
class A
{
    public:
    A & operator = ( int b)
    {
        myint = b;
        return *this;
    }
    int myint;
};
int main()
{
    A a=1;
    cout<<"int="a.myint<<endl;
    return 0;
}

很简单,能看出问题吗?反正我是没有发现。慢慢看吧。

用简单的make命令,发现编译通不过:

%make test
c++ -O -pipe test.cpp -o test
test.cpp: In function `int main()':
test.cpp:15: conversion from `int' to non-scalar type `A' requested
*** Error code 1

不是已经重载了吗?为什么还需要从int到class A的转化呢?

问题的解决

如果把main函数改成下面的代码:

int main()
{
    A a;
    a = 1;
    cout<<"int="a.myint<<endl;
    return 0;
}

然后再编译运行:

%make test
c++ -O -pipe test.cpp -o test
%./test
int=1

啊哈,终于解决了。原来在声明变量的时候是需要调用构造函数,而不是赋值函数。

为什么在系统自己的函数中可以这样呢?例如使用STL中的string(关于STL学习参看Center of STL Study)

#include <string>
#include <iostream>
int main()
{
   string strtmp="my string";
   cout<<strtmp<<endl;
   return 0;
}

再改改咱们的class A的代码,增加两个函数试试:

#include <iostream>
class A
{
    public:
    A(){}
    A(int b){myint=b;}
    A & operator = ( int b)
    {
        myint = b;
        return *this;
    }
    int myint;
};
int main()
{
    A a;
    a = 1;
    A b=2;
    cout<<"inta="<<a.myint<<"\tintb="<<b.myint<<endl;
    return 0;
}

编译并运行,你会发现你想要的结果:

%make test
c++ -O -pipe test.cpp -o test
%./test
inta=1 intb=2

具体为什么?

如果是使用A b=2;调用的过程是调用构造函数A(int b)。

附加:

如果这样写代码,

int *  pA, pB;
int tmp=2;
pB = &tmp;
cout<<*pB<<endl;

发现pB实际上不是指针。需要改成:

int *  pA, *pB;
int tmp=2;
pB = &tmp;
cout<<*pB<<endl;

估计是我对C++了解不够,需要努力啊。

 

由 winter 发表于 December 30, 2004 09:39 PM