About "const" problem

L

liguoqiang_0121

Hi,all
Please look program.
class AA
{
public:
void hello();
};
void AA::hello()
{
printf("this is class AA\n");
}
void display(const AA& s)
{
s.hello();
}
int main()
{
AA a;
display(a);
return 0;
}
I got some errors when compiling
Compiling...
main.cpp
D:\my_project\testcpp\main.cpp(17) : error C2662: 'hello' : cannot
convert 'this' pointer from 'const class AA' to 'class AA &'
Conversion loses qualifiers
Error executing cl.exe.

Who can tell me the reason. Appreciate for any advice.
 
J

Jerry Coffin

@f6g2000cwb.googlegroups.com>, (e-mail address removed)
says...
Hi,all
Please look program.
class AA
{
public:
void hello();
};
void AA::hello()

You've made 'hello' a non-const function, so it can only
be invoked for a non-const object.
{
printf("this is class AA\n");
}
void display(const AA& s)

Here, you're receiving a reference to a const object, so
you can only use it to invoke const member functions.

Since your 'hello' member function doesn't modify the
state of the object, you can make it a const member
function:

struct AA {
void hello() const {
// why did you use printf?
printf("This is class AA\n");
}
};
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top