c++ - 使用指针访问 cpp 中的私有(private)值

标签 c++ accessor

由于某些原因,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::ostreamvoid 传递给运算符。

关于c++ - 使用指针访问 cpp 中的私有(private)值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21947485/

相关文章:

perl - 如何在perl的对象中制作 "universal"getter和setter?

c++ - 在 vector C++ 中查找坐标

c++ - CFile::modeCreate 没有像宣传的那样工作

c++ - 如何检查文件是否为常规文件?

.net - 是否可以通过覆盖来将访问器添加到 .NET 中的属性?

c++ - 可以在重载运算符中使用访问器方法吗?

c++ - Qt 在 QTableView 中设置自定义小部件

c++ - VS2010 上的 MySQL Connector C 链接问题

c# - 在 C# 中,如何仅在类属性不存在的情况下生成值?

ruby-on-rails - Rails ActiveRecord 存储中的动态属性