由于某些原因,getter 方法不起作用。它们是公开的,所以我不知道出了什么问题。
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();
嗯,有什么方法可以解决最后一个问题的(int) (it->getLength())
我们可以为另一个做吗:
std::ostringstream value;
value << (*it).getName();
cout << getName << endl;
最佳答案
只需将 getter 声明为 const
:
class Document
{
public:
std::string getName() const;
int getLenght() const;
};
并指定它们的返回值。
错误信息不是很可读,但是在 gcc 中:
error: passing A as B argument of C discards qualifiers
几乎总是由尝试修改 const
的内容引起。
但是其他信息很清楚:
error: no match for 'operator<<'
(operand types are 'std::ostream {aka std::basic_ostream}' and 'void')
cout << it->getName() << endl;
也就是说,您正在尝试将 std::ostream 和 void 传递给运算符。
关于c++ - 使用指针访问 cpp 中的私有(private)值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21947485/