【问题标题】:Accessing private values in cpp using pointers使用指针访问 cpp 中的私有值
【发布时间】:2014-03-23 17:43:01
【问题描述】:

由于某种原因,getter 方法不起作用。它们是公开的,所以我不知道出了什么问题。

for (std::vector<Document>:: const_iterator it = v.begin(); it != v.end(); ++it)
{
    cout << it->getName() << endl;
    counter += it->getLength();
}

错误:将 'const Document' 作为 'void Document::getName()' 的 'this' 参数传递会丢弃限定符 [-fpermissive] cout getName()

错误:'operatorgetName()

错误:将 'const Document' 作为 'void Document::getLength()' 的 'this' 参数传递会丢弃限定符 [-fpermissive] 计数器 += it->getLength();

错误:“int”和“void”类型的无效操作数到二进制“operator+” 计数器 += it->getLength();

嗯,有没有办法让我们为最后一个问题做(int) (it-&gt;getLength())

我们可以为另一个做吗:

std::ostringstream value;   
value << (*it).getName();
cout << getName << endl;     

【问题讨论】:

  • 他们不是const,所以你不能用const_iterator 给他们打电话。它与可访问性无关,与 const 正确性有关。而且您无法打印返回 void 的结果。
  • 嗯,好的,但其他两个问题仍然存在。 +1 快速评论。
  • 其中一个解决了两个错误,如果您想学究气,我也可以说您不能将返回 void 的结果添加到其他内容中。我没有看到其他问题。
  • 为什么它会返回 void 呢?啊,没关系,我很傻,哈哈

标签: c++ accessor


【解决方案1】:

只需将 getter 声明为 const:

class Document
{
public:
    std::string getName() const;
    int getLenght() const;
};

并指定它们的返回值。

错误信息不是很可读,但是在gcc中:

error: passing A as B argument of C discards qualifiers 

几乎总是由尝试修改 const 引起的。

其他信息很清楚:

错误:'operator (操作数类型是 'std::ostream {aka std::basic_ostream}' 和 'void')
cout getName()

也就是说,您正在尝试将 std::ostreamvoid 传递给操作员。

【讨论】:

  • 知道为什么两者都是无效的吗?
【解决方案2】:

虽然您没有显示相关代码,但错误消息显示足以很好地猜测问题。

你的班级显然是这样的:

class Document { 
// ...
public:
    void getName() { /* ... */ }   
    void getLength() { /* ... */ }
    // ...
};

要解决此问题,您需要将 getNamegetLength 更改为 1) 返回值,以及 2) 成为 const 成员函数,按照这个一般顺序:

class Document { 
// ...
public:
    std::string getName() const { /* ... */ }   
    size_t getLength() const { /* ... */ }
    // ...
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-03
    • 1970-01-01
    相关资源
    最近更新 更多