簡體   English   中英

為什么'operator <<(cout,double)'不起作用?

[英]Why doesn't 'operator<<(cout, double)' work?

我正在研究重載運算符。 我沒有區分在double / std::string上使用<< -operator。

int main()
{
    double a = 12;
    string s = "example";

    operator<<(cout, a); //doesn't work
    cout.operator<<(a);  //works

    operator<<(cout, s); //works
    cout.operator<<(s);  //doesn't work   
}    

為什么不是operator<<(cout, a)cout.operator<<(s); 工作?

因為該運算符被定義為成員函數,而不是自由函數。

操作符可以通過這兩種方式重載,與常規操作符語法一起使用時,對用戶來說是透明的。 但是,使用顯式語法時,必須使用特定於實際函數定義的語法。

此示例顯示了實踐中的差異:

class Stream {
    Stream& operator<<(Inside);
};

Stream& operator<<(Stream&, Outside);

對於std::string ,使用Outside方式。 對於doubleInside是。

您可以通過兩種不同的方式定義運算符,作為類的成員和具有兩個參數的獨立函數。

接受double值的運算符實現為std::ostream的成員函數,請參閱cpp reference 你會注意到char const*std::string沒有重載。 這些是作為獨立功能單獨定義的。

那些定義為成員(僅!)的運算符使用cout.operator<<(argument)表示法,具有雙參數變體的獨立運算符。

但是,如果您按預期使用運算符,則會隱藏所有這些差異:

std::cout << whatEver;

因為類型std :: basic_ostream&和double(或const double&)的非類運算符<<未在C ++中定義。

這種帶有double類型參數的運算符在類std :: basic_ostream中聲明為成員函數。

basic_ostream<charT, traits>& operator<<(double f);

對於std :: string類型的對象,運算符按以下方式聲明為獨立(非類成員)函數

template<class charT, class traits, class Allocator>
basic_ostream<charT, traits>&
operator<<(basic_ostream<charT, traits>& os,
const basic_string<charT, traits, Allocator>& str);

std::basic_ostream提供了一些<<實現(對於基本類型)作為成員函數。 對於其他類型(例如對於std::basic_string ), operator <<實現為自由函數。 這就是標准規定的方式。

如果您使用顯式函數調用表示法(如代碼中)調用運算符,這只是一個問題。 使用它的自然方式是使用運算符表示法( cout << x ),其中問題不會發生,因為成員和自由函數都可以被它調用。

您沒有以正確的方式使用運算符。

運營商可以實施為會員職能或非會員。

跑步的時候

 cout.operator <<(a);
 cout << a;
 cout.operator <<(s);
 cout << s;

你正在調用類操作符實現;

但是當你打電話的時候

operator<<(cout, a);

實施在哪里? O_O

工作示例測試了vc ++ 13& gcc(這里)

#include <iostream>

using std::cin;
using std::cout;
using std::endl;

int main(int argc, char* argv[])
{
   int number = 13;
   float pi = 3.13f;
   double dp = 2.23233;


   cout << "number: " << number << endl;
   cout << "pi: " << pi << endl;
   cout << "double: " << dp << endl << endl;


   cout.operator <<(number) << endl;
   cout.operator <<(pi) <<  endl;
   cout.operator <<(dp);
}

注釋是否需要示例類型的成員或非成員實現。

暫無
暫無

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

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