Reputation: 219
I have write a very simple program about const class, however, when I compile, there is a error:void Test::printxy(void)' : cannot convert 'this' pointer from 'const Test' to 'Test &'
The program is as below
#include <iostream>
using namespace std;
class Test
{
private:
int x, y;
public:
Test(int a = 1, int b = 1) : x(a), y(b) {};
void printxy();
};
void Test::printxy()
{
cout << "x*y=" << x*y << endl;
}
void main(void)
{
const Test t;
t.printxy();
system("pause");
}
Upvotes: 1
Views: 243
Reputation: 153955
You try to call the non-const
function printxy()
on the const
obejct t
. You are missing a const
after the method declaration:
class Test {
// ...
void printxy() const;
};
void Test::printxy() const {
// ...
}
Upvotes: 1
Reputation: 477358
Since the printxy
member function is not declared const
, it cannot be invoked on a constant object. You need to declare the member function const
like this:
class Test
{
void printxy() const;
// ^^^^^
// ...
};
void Test::printxy() const
{
// ...
}
Upvotes: 3