简体   繁体   中英

static member function error in c++

If static class member and static class function has a class scope then why can't I access the display function(it shows error)? If in place of display function I write count it displays the correct value ie, 0

#include <iostream>
#include <string> 

using namespace std;

class Person
{
    public:
     static int Length;
     static void display()
     {
        cout<< ++Length;
     }
};

int Person::Length=0;

int main()
{
   cout<< Person :: display(); //error
   // Person :: Length shows correct value
   return 0;
}

You can call the display function, your error is that you are trying to output the result to cout . Person::display doesn't return anything, hence the error.

Just change this:

cout<< Person :: display(); //error

To this:

Person::display();

If you want to pipe objects into streams, you need to define an appropriate operator <<, like this:

#include <iostream>
#include <string> 

using namespace std;

class Person
{
    public:
     class Displayable {
         template< typename OStream >
         friend OStream& operator<< (OStream& os, Displayable const&) {
             os << ++Person::Length;
             return os;
         }
     };
     static int Length;
     static Displayable display() { return {}; }
};

int Person::Length=0;

int main()
{
   cout<< Person :: display(); //works
   // Person :: Length shows correct value
   return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM