Question

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;     
Was it helpful?

Solution

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.

OTHER TIPS

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 { /* ... */ }
    // ...
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top