| University of Cambridge > Engineering Department > computing help > Languages > C++ |
int i; c test_class; i=7; test_class.f(i); cout << "i=" <<i << endl;
#include <iostream>
using namespace std;
class c
{
public:
int value;
void f(const int& arg) const;
};
// this is a member function of c
void c::f(const int& arg) const {
cout << "arg=" << arg << endl;
// The next 2 lines are commented out - they're errors.
// arg=9;
// value=9;
}
int main()
{
int i;
c test_class;
i=7;
test_class.f(i);
cout << "i=" << i << endl;
}
void g() {
int i;
c test_class;
i=7;
test_class.f(&i);
}
In none of these cases is i copied to a new variable.
#include <iostream>
using namespace std;
class c
{
public:
int value;
void f(const int * const arg);
};
// this is a member function of c
void c::f(const int * const arg) {
cout << "*arg=" << *arg << endl;
// The next 2 lines are commented out - they're errors.
// arg=9;
// *arg=9;
value=9; // This is ok
}
int main()
{
int i;
c test_class;
i=7;
test_class.f(&i);
cout << "i=" << i << endl;
}
#include <iostream>
using namespace std;
class c
{
public:
int value;
const int* f();
};
int* c::f() {
int j=999;
cout << "j=" << j << endl;
// The following line of code returns a pointer to the integer j.
// Unfortunately j is a local variable whose memory is available
// for recycling once the function's finished. This recycling
// might not happen straight away, but when it does, the 999
// value could be overwritten.
// The line is legal, though some compilers (including the one
// our students use) give a warning.
return &j;
}
int main()
{
int *ip;
c test_class;
ip=test_class.f();
cout << "*ip=" << *ip << endl;
}
const int* c::f(const int * const arg) const;is a legal declaration. First work out what it means, then write a program which tests to see if your compiler faithfully obeys each of the uses of const.
| | 1A C++ Frequently Asked Questions | C++ | Languages | computing help | |