关于运算法重载的问题~!
#include <iostream>
using namespace std;
class Test
{
public:
Test(int a=0)
{
Test::a=a;
}
Test(Test &temp)
{
cout<<"载入拷贝构造函数"<<"|"<<temp.a<<endl;
Test::a=temp.a;
}
~Test()
{
cout<<"载入析构函数!"<<endl;
cin.get();
}
Test operator +(Test& temp2)
{
cout<<this->a<<endl;
Test result(this->a+temp2.a);
return result;
}
Test& operator ++()
{
this->a++;
return *this;
}
public:
int a;
};
int main(int argc,char* argv[])
{
Test a(100);
Test c=a+a;
cout<<c.a<<endl;
c++;
cout<<c.a<<endl;
++c;
cout<<c.a<<endl;
++(++c);
cout<<c.a<<endl;
cin.get();
}
Test(const Test &temp)
Test operator ++(int)
{
// 2.1)可以这么做
Test ret(a++);
// 2.2)也可以这样 Test ret(a); ++a;
// 代码其实可以任意写,不过后缀++的语义,是对象自增,返回自增前的值 ......
// 符合运算符的语义的运算符重载,才是你所需要的。
return ret;
}
class Test{
//
public:
// Test(int a=0)
// {
// Test::a=a;//这样可能没有错误,不过很少人这样写。
// }
//多半是这样写:
Test(int a=0):a(a){}
//或者这样写:
// Test(int a = 0)
// {
// this->a = a;//这样是为了区分成员变量和形参,
// 一般来说,形参不要和成员变量同名,以免遮蔽同名的成员变量。
// }
// 拷贝构造函数,一般传递常量引用。
Test(const Test &temp)
{
cout<<"载入拷贝构造函数"<<"
[解决办法]
"<<temp.a<<endl;
//Test::a=temp.a; //这里加类名是多余的。
a = temp.a; //这样写就成。
}
~Test()
{
cout<<"载入析构函数!"<<endl;
cin.get();
}
Test& operator ++()
{
this->a++;
return *this;
}
Test& operator ++()
{ Test ret(*this);
++ (*this);
return ret;
}
public://一般就用private:了,不过你这里要在main 里用到,马马虎虎,可以这么做。
//类的成员变量,多数时候,都是 private 或者protected 的。
int a;
};
int main(int argc,char* argv[])
{
Test a(100);
Test c=a+a;
cout<<c.a<<endl;
c++;
cout<<c.a<<endl;
++c;
cout<<c.a<<endl;
++(++c);
cout<<c.a<<endl;
cin.get();
return 0; //C++ 要求带返回值的函数,必须返回一个值。
}