簡體   English   中英

我什么時候在 ZF6F87C9FDCF8B3713F07F93F14Z 中制作 function 和 class 成員 function

[英]When do I make a function a class member function in C++?

I am fairly new to programming and am confused over when I should make a function a member function of a class or just use member getter functions to access the private members of the class. 我想怎么做都可以。

考慮以下:

#include <iostream>
#include <string>
using namespace std;

class Person
{  
  string name;
  int age;
public:
  Person()
    : name("James"), age(30)
  {};
  void Print();
  string GetName(Person& person) { return name;};
  int GetAge(Person&) { return age;};
};

void Person::Print() // member function
{
 cout << "Using member function: " << name << ", " << age << endl;
}

void Print(Person& person) // non-member function 
{
 cout << "Using non-member function: " << person.GetName(person) << ", " << person.GetAge(person) << endl;
}

int main() 
{
Person test_person; //default constructor
test_person.Print(); // member function
Print(test_person); // non-member function

return 0;
}

output 對於成員 function Person::Print()或非成員 function Print()是相同的,即程序產生:

Using member function: James, 30
Using non-member function: James, 30

然后您可以清楚地編寫一個非成員 function ,它使用成員 getter 函數來訪問 class 的私有成員,因此您可以使用任何一種方式。

It seems to me like making Print() a member function of class Person is the way to go since the function is clearly specific to the class and its private data and will probably want to be used by someone else if they use the class.

那正確嗎? 我還應該考慮什么?

您的代碼類似於以下代碼:

private:
 string name;
 int age;

這些屬性只能在 class object 內部訪問。 不能從 object 外部調用,只能使用 geter()、seter() 來獲取、設置 object 的值。

如果使用公共屬性,則類似於 C/C++ 上的struct結構

我認為您可能需要考慮再看一下access modifiers 您不能修改 class 的privateprotected數據成員。 因此,您需要它們的成員函數。

成員函數優於非成員函數。 假設您將名稱從Print更改為Log並且您忘記了該名稱。 對於大多數 IDE,可以通過鍵入“.”輕松查找成員 function。 然后找到正確的,而非會員 function 將需要幾次按鍵猜測才能找到正確的。

我還要說成員函數在許多情況下使用起來更直觀。

實施兩者也不被認為是不好的做法。 例如,對於std::vector v ,有成員 function v.size()以及通用非成員 function std::size(v)

暫無
暫無

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

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