-> mutable을 사용해야 함.
#include <stdio.h>
#include <iostream>
using namespace std;
class Point
{
private :
int a_, b_;
mutable char data[16];
mutable bool bchange;
public :
Point(int _a, int _b) : a_(_a), b_(_b), bchange(false){}
char* toString() const
{
if (!bchange)
{
bchange = true;
sprintf(data, "%d, %d", a_, b_);
}
return data;
}
};
int main()
{
const Point p(1, 2);
cout << p.toString() << endl;
}
-> 분리함.
#include <stdio.h>
#include <iostream>
using namespace std;
struct Data
{
char name[16];
bool bchange;
};
class Point
{
private :
int a_, b_;
Data *data;
public :
Point(int _a, int _b) : a_(_a), b_(_b)
{
data = new Data;
data->bchange = false;
}
char* toString() const
{
if (!data->bchange)
{
data->bchange = true;
sprintf(data->name, "%d, %d", a_, b_);
}
return data->name;
}
};
int main()
{
const Point p(1, 2);
cout << p.toString() << endl;
}