方法是 OOP 概念中的過程或函數。而函數是一組可重用的代碼,可以在程序的任何地方使用。這有助於需要一次又一次地編寫相同的代碼。它幫助程序員編寫模塊化代碼。
方法:
- 方法也和函數一樣工作。
- 方法是在類中定義的。例如:Java 中的 main()
- 方法可以是私有的、公共的或受保護的。
- 該方法僅由其引用/對象調用。例如:如果類具有 obj 作為對象名稱,則該方法通過以下方式調用:
obj.method();
- 方法能夠對類中包含的數據進行操作
- 每個對象都有自己的方法,該方法存在於類中。
- 一個函數是一個語句塊,它接受特定的輸入,進行一些計算,最後產生輸出。
- 一個函數是獨立定義的。例如:C++ 中的 main()
- 默認情況下,函數是公共的。
- 它可以在整個程序的任何地方訪問。
- 它是由它的名字命名的。
- 如果需要,它可以返回值。
- 如果定義了一個函數,那麽它對於每個已創建的對象都是相同的。
下麵是說明 C++ 中的函數和方法的程序:
程序1:
// C++ program to illustrate functions
#include "bits/stdc++.h"
using namespace std;
// Function Call to print array elements
void printElement(int arr[], int N)
{
// Traverse the array arr[]
for (int i = 0; i < N; i++) {
cout << arr[i] << ' ';
}
}
// Driver Code
int main()
{
// Given array
int arr[] = { 13, 15, 66, 66, 37,
8, 8, 11, 52 };
// length of the given array arr[]
int N = sizeof(arr) / sizeof(arr[0]);
// Function Call
printElement(arr, N);
return 0;
}
輸出:
13 15 66 66 37 8 8 11 52
程序2:
// C++ program to illustrate methods
// in class
#include "bits/stdc++.h"
using namespace std;
// Class GfG
class GfG {
private:
string str = "Welcome to GfG!";
public:
// Method to access the private
// member of class
void printString()
{
// Print string str
cout << str << '\n';
}
};
// Driver Code
int main()
{
// Create object of class GfG
GfG g;
// Accessing private member of
// class GfG using public methods
g.printString();
return 0;
}
輸出:
Welcome to GfG!
程序3:
// C++ program to illustrate methods
// and functions
#include <iostream>
using namespace std;
// Function call to return string
string offering(bool a)
{
if (a) {
return "Apple.";
}
else {
return "Chocolate.";
}
}
// Class Declaration
class GFG {
public:
// Method for class GFG
void guest(bool op)
{
if (op == true) {
cout << "Yes, I want fruit!\n";
}
else {
cout << "No, Thanks!\n";
}
}
};
// Driver Code
int main()
{
bool n = true;
cout << "Will you eat fruit? ";
// Create an object of class GFG
GFG obj;
// Method invoking using an object
obj.guest(n);
if (n == true) {
// Append fruit using function
// calling
cout << "Give an " + offering(n);
}
// Giving fruit..Function calling
else {
// Append fruit using function
// calling
cout << "Give a " + offering(n);
}
return 0;
}
輸出:
Will you eat fruit? Yes, I want fruit! Give an Apple.
相關用法
- C++ Math scalbn()用法及代碼示例
- C++ Map erase()用法及代碼示例
- C++ Math asinh()用法及代碼示例
- C++ Math isgreater()用法及代碼示例
- C++ Map rend()用法及代碼示例
- C++ Math fabs()用法及代碼示例
- C++ Math acosh()用法及代碼示例
- C++ Math islessgreater()用法及代碼示例
- C++ Math log2()用法及代碼示例
- C++ Math log()用法及代碼示例
- C++ Map crend()用法及代碼示例
- C++ Map multimap()用法及代碼示例
- C++ Math nearbyint()用法及代碼示例
- C++ Map count()用法及代碼示例
- C++ Map clear()用法及代碼示例
- C++ Map cend()用法及代碼示例
- C++ Math tan()用法及代碼示例
- C++ Map crbegin()用法及代碼示例
- C++ Math nextafter()用法及代碼示例
- C++ Map emplace()用法及代碼示例
注:本文由純淨天空篩選整理自GeeksforGeeks大神的英文原創作品 Methods vs. Functions in C++ with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。