代碼:
#include "stdafx.h"
#include
class X {
int i;
public:
X();
int x();
void x(int x);
};
X::X()
{
i = 1;
}
int X::x()
{
return i;
}
void X::x(int x)
{
i = x;
}
X f()
{
return X();
}
void g1(X& x)
{
// cout << " non-const reference:" << x.x() << endl;
}
void g2(const X& x)
{
// cout << " const reference:" << ends << "get x.i:" << x.x() << endl;
// int temp =3;
// cout << "set x.i:" << temp << endl;
// x.x(temp);
// cout << "get x.i:" << x.x() << endl;
}
int main(int argc, char* argv[])
{
g1(f());
g2(f());
return 0;
}
將成元函數改成const的然后調用:
#include "stdafx.h"
#include
class X {
int i;
public:
X();
int x()
void x(int x);
};
X::X()
{
i = 1;
}
int X::x()
return i;
}
void X::x(int x)
{
i = x;
}
X f()
{
return X();
}
void g1(X& x)
{
cout << " non-const reference:" << x.x() << endl;
}
void g2(const X& x)
{
cout << " const reference:" << ends << "get x.i:" << x.x() << endl;
// int temp =3;
// cout << "set x.i:" << temp << endl;
// x.x(temp);
// cout << "get x.i:" << x.x() << endl;
}
int main(int argc, char* argv[])
{
g1(f());
g2(f());
return 0;
}
注:如果聲明一個成員函數為const函數,則等于告訴編譯器可以為一個const對象調用這個函數。非
即改為如下是不對的:
#include "stdafx.h"
#include <iostream.h>
class X {
int i;
public:
X();
int x() const;
void x(int x) const ;
};
X::X()
{
i = 1;
}
int X::x() const
{
return i;
}
void X::x(int x) const
{
i = x;
}
X f()
{
return X();
}
void g1(X& x)
{
cout << " non-const reference:" << x.x() << endl;
}
void g2(const X& x)
{
cout << " const reference:" << ends << "get x.i:" << x.x() << endl;
int temp =3;
cout << "set x.i:" << temp << endl;
// x.x(temp);
cout << "get x.i:" << x.x() << endl;
}
int main(int argc, char* argv[])
{
g1(f());
g2(f());
return 0;
}