Accessing private values in cpp using pointers
For some reason the getter methods doesn't work. They are public, so I have no idea what's wrong.
for (std::vector<Document>:: const_iterator it = v.begin(); it != v.end(); ++it)
{
cout << it->getName() << endl;
counter += it->getLength();
}
error: passing 'const Document' as 'this' argument of 'void Document::getName()' discards qualifiers [-fpermissive] cout << it->getName() << endl;
error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream}' and 'void') cout << it->getName() << endl;
error: passing 'const Document' as 'this' argument of 'void Document::getLength()' discards qualifiers [-fpermissive] counter += it->getLength();
error: invalid operands of types 'int' and 'void' to binary 'operator+' counter += it->getLength();
Hmm, is there a way to can we do (int) (it->getLength())
for the last problem
and can we do for the other one:
std::ostringstream value;
value << (*it).getName();
cout << getName << endl;
Just declare the getters to be const
:
class Document
{
public:
std::string getName() const;
int getLenght() const;
};
and specify their return values.
The error messages are not very readable, but in gcc :
error: passing A as B argument of C discards qualifiers
is almost always caused by trying to modify something that is const
.
The other messages are clear however:
error: no match for 'operator<<'
( operand types are ' std::ostream {aka std::basic_ostream}' and ' void ')
cout << it->getName() << endl;
that is you are trying to pass a std::ostream and void to an operator.
Although you don't show the relevant code, the error messages show enough to take a pretty good guess at the problem.
Your class apparently looks something like this:
class Document {
// ...
public:
void getName() { /* ... */ }
void getLength() { /* ... */ }
// ...
};
To fix the problem, you need to change getName
and getLength
to 1) return values, and 2) be const
member functions, something on this general order:
class Document {
// ...
public:
std::string getName() const { /* ... */ }
size_t getLength() const { /* ... */ }
// ...
};
链接地址: http://www.djcxy.com/p/90140.html
上一篇: 在C ++中调用基本成员函数模板模糊性
下一篇: 使用指针访问cpp中的私有值