c++中的静态成员函数错误

static member function error in c++

本文关键字:函数 错误 静态成员 c++      更新时间:2023-10-16

如果静态类成员和静态类函数有类作用域,那么为什么我不能访问显示函数(它显示错误)?如果代替显示功能I写入计数,则显示正确的值,即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;
}

可以调用display函数,您的错误是试图将结果输出到coutPerson::display没有返回任何内容,因此出现错误。

只需更改:

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

对此:

Person::display();

如果要将对象管道传输到流中,则需要定义适当的运算符<lt;,像这样:

#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;
}