问题一:const修饰的是谁?
实验代码如下:
class Test
{
public:
Test(int a, int b)
{
this->a = a;
this->b = b;
}
void Var(int a,int b) const //const修饰的this指针。,Var(const Test *this,int a,int b )
{
this->a = 100;
this->b = 188;
cout << a << endl;
}
private:
int a;
int b;
};
int main()
{
Test t1(20, 10);
t1.Var(100, 200);
system("pause");
return 1;
}
说明:上面的 this->a = 100; this->b = 188; 是错误的,因为const修饰的this指针,再次修改这个值的时候就出现了错误。
全局函数PK成员函数
全局函数转换成员函数少了一个参数。
代码:
class Test
{
public:
int a;
int b;
public:
Test TestAdd(Test &a1)
{
Test tmp(this->a + a1.a, this->b + a1.b);
return tmp;
}
public:
Test(int a=0, int b=1)
{
this->a = a;
this->b = b;
}
public:
void printT()
{
cout << a << b << endl;
}
private:
};
//全局函数的方法。实现t1+t2;
Test TestAdd(Test &a1, Test &a2)
{
Test tp;
return tp;
}
void printT(Test *pT)
{
cout << pT->a << endl;
}
int main()
{
Test t1(1, 2);
Test t2(2, 3);
Test t3;
t3 = TestAdd(t1, t2); //调用全局函数。
t3= t1.TestAdd(t2);
t3.printT();
system("pause");
return 1;
}