簡體   English   中英

C ++中的靜態成員函數錯誤

[英]static member function error in c++

如果靜態類成員和靜態類函數具有類范圍,那么為什么我不能訪問顯示函數(顯示錯誤)? 如果我代替顯示功能,我寫了count,它將顯示正確的值,即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函數,您的錯誤是您試圖將結果輸出到cout Person::display不返回任何內容,因此會出錯。

只需更改此:

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

對此:

Person::display();

如果要將對象通過管道傳遞到流中,則需要定義適當的運算符<<,如下所示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM