簡體   English   中英

朋友功能無法訪問C ++類的成員

[英]Friend function not able to access member of class C++

我試圖將運算符“ <<”作為朋友函數重載,但由於某種原因,它無法訪問該類的成員。 為什么朋友功能不能訪問isEmpty()countcall_DB [] 這是我寫的代碼:

#include <iostream>
#include <string>
using namespace std;
class callRecord
{
public:
   string firstname;
   string lastname;
   string cell_number;
   int relays;
   int call_length;
   double net_cost;
   double tax_rate;
   double call_tax;
   double total_cost;
};

class callClass
{
public:

   bool isEmpty();
   friend ostream & operator<<(ostream & out, callClass &Org);

private:
   int count;
   int size;
   callRecord *call_DB;
};

bool callClass::isEmpty()
{
   if (count == 0)
   {
       return 1;
   }
   else
   {
       return 0;
   }
}

ostream & operator<<(ostream & out, callClass &Org)
{
   if (isEmpty() == 1)
   {
       cout << "The array is empty" << endl;
   }
   else
   {
       out.setf(ios::showpoint);
       out.setf(ios::fixed);
       out.precision(2);

   for (int i = 0; i < count; i++)
       {
           out << setw(10) << call_DB[i].firstname << " ";
           out << setw(10) << call_DB[i].lastname << " ";
           out << call_DB[i].cell_number << "\t";
           out << call_DB[i].relays << "\t";
           out << call_DB[i].call_length << "\t";
           out << call_DB[i].net_cost << "\t";
           out << call_DB[i].tax_rate << "\t";
           out << call_DB[i].call_tax << "\t";
           out << call_DB[i].total_cost << endl;
       }
   }
}

謝謝。

您的operator<<函數是全局函數,而不是callClass的成員。 要訪問這些字段,您需要使用Org.call_DBOrg.countOrg.isEmpty();

因為您沒有將那些成員“限定”為實例。 你需要寫

ostream & operator<<(ostream & out, callClass &Org)
{
    if (Org.isEmpty() == 1)
//      ^^^^^

Org.countOrg.call_DB等..

請記住,您的operator<<全局函數,而不是成員函數。 否則,您首先無需將其聲明為朋友。

為什么朋友功能不能訪問isEmpty(),count和call_DB []?

因為您不了解“訪問”的含義。 這並不意味着friend function成為該類的方法,因此您不能在嘗試時隱式使用this ,而應使用Org參數:

out << setw(10) << Org.call_DB[i].firstname << " "; 

其余的都一樣。

您的朋友函數不是成員函數,因此沒有“ this”可用。 您的操作員代碼應類似於:

ostream & operator<<(ostream & out, callClass &Org)
{
   for (int i = 0; i < count; i++)
       {
           out << Org.call_DB[i] << endl;
       }
   }
}

然后還必須為callRecord提供運算符<<

暫無
暫無

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

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