首页 文章

使用指针访问cpp中的私有值

提问于
浏览
0

由于某种原因,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 << it-> getName()<< endl;错误:'operator <<'不匹配(操作数类型是'std :: ostream '和'void')cout << it-> getName()<< endl;错误:将'const Document'作为'void Document :: getLength()'的'this'参数传递,丢弃限定符[-fpermissive] counter = it-> getLength();错误:类型'int'和'void'的无效操作数到二元'运算符'counter = it-> getLength();

嗯,有没有办法可以为最后一个问题做 (int) (it->getLength())

我们可以为另一个做:

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

2 回答

  • 2

    只需声明getter为 const

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

    并指定它们的 return 值 .

    错误消息不是很易读,但在_1443146中:

    error: passing A as B argument of C discards qualifiers
    

    几乎总是由于尝试修改 const 而引起的 .

    但是其他消息很清楚:

    错误:'operator <<'不匹配(操作数类型是'std :: ostream '和'void')cout << it-> getName()<< endl;

    那就是你试图将 std::ostreamvoid 传递给运算符 .

  • 1

    虽然您没有显示相关代码,但错误消息显示足以对问题进行很好的猜测 .

    你的 class 显然看起来像这样:

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

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

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

相关问题