By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,918 Members | 2,294 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,918 IT Pros & Developers. It's quick & easy.

About "const" problem

P: n/a
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.

Jun 18 '06 #1
Share this Question
Share on Google+
1 Reply


P: n/a
In article <1150598506.125103.124970
@f6g2000cwb.googlegroups.com>, li*************@sina.com
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");
}
};

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jun 18 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.