我一直在尝试实现包含MyString类对象的Stack(这是其中一本书的练习)。我设法将这些对象推送到容器,但是当我想调用函数void print()时,我收到一个错误:
错误:将'const MyString'作为'void MyString :: print()'的'this'参数传递,丢弃限定符[-fpermissive] CP->打印();
以下是代码:
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
class MyString
{
string a;
public:
MyString(string aa) : a(aa)
{
}
void print()
{
cout << a << endl;
}
};
class StringStack {
static const int size = 100;
const MyString* stack[size];
int index;
public:
StringStack();
void push(const MyString* s); // does this have to be const?
const MyString* pop(); // does this have to be const?
};
StringStack::StringStack() : index(0) {
memset(stack, 0, size * sizeof(MyString*));
}
void StringStack::push(const MyString* s) {
if(index < size)
stack[index++] = s;
}
const MyString* StringStack::pop() {
if(index > 0) {
const MyString* rv = stack[--index];
stack[index] = 0;
return rv;
}
return 0;
}
MyString s0("pralines & cream");
MyString s1("fudge ripple");
MyString s2("jamocha almond fudge");
MyString s3("wild mountain blackberry");
MyString s4("raspberry sorbet");
MyString s5("lemon swirl");
MyString s6("rocky road");
MyString s7("deep chocolate fudge");
MyString iceCream[] = {s0,s1,s2,s3,s4,s5,s6,s7};
const int iCsz =
sizeof iceCream / sizeof *iceCream;
int main() {
StringStack ss;
for(int i = 0; i < iCsz; i++)
ss.push(&iceCream[i]);
const MyString* cp;
while((cp = ss.pop()) != 0)
{
cout << (long)cp << endl;
// cp->print(); // won't work
}
} ///:~
答案 0 :(得分:0)
你可以:
void MyString::print()
const,这似乎是合理的。或:
const MyString* pop();
返回非常量指针。我不认为StringStack
应存储指向const对象的指针。如果您打算永远不要从堆栈中修改MyString
个对象,请将它们内部保留为const
。选择取决于您的要求。