[英]Cannot call member function without object c++ Crypto Program
該程序應該是一個帶有類的加密程序,我收到錯誤消息:
Crypto.cc:74:53: 錯誤:無法調用沒有對象的成員函數 'std::string Cipher::Encrypt(std::string, int)'
#include <iostream>
using namespace std;
class Cipher {
public:
string str;
string Encrypt(string data, int key) // First example, shifting through an array (or in our case, a string)
{
string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; //Every letter in the alphabet(upper & lower case), and numbers 0-9
int shiftPos; //The position of the shift
bool shift = false; //Whether it is in our alphabet or not
for(int i = 0; i < data.length(); i++) //Encrypt each character in the string
{
for(int j = 0; j < chars.length(); j++) //Check each character in our char list for a match against the data string
if(data[i] == chars[j]) //If we find a match
{
shift = true; //Set the shift for this character to true
shiftPos = j; //The position in the array
}
if(shift) //Only if it was found in our character list (chars)
{
shiftPos += key; //Add the key to the shift position
shiftPos %= chars.length(); //Modulo the value so it doesn't go out of bounds
data[i] = chars[shiftPos]; //Set our new value
}
shift = false; //Set to false for next recursion
}
return data; //return the modified string
}
string Decrypt(string data, int key)
{
string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
int shiftPos;
bool shift = false;
for (int i=0; i < data.length(); i++)
{
for(int j = 0; j < chars.length(); j++)
if (data[i] == chars[j])
{
shift = true;
shiftPos = j;
}
if(shift)
{
shiftPos -= key;
shiftPos %= chars.length();
data[i] = chars[shiftPos];
}
shift = false;
}
return data;
}
};
int main()
{
string str;
int key = 8;
cout << "Enter a string to encrypt: ";
getline(cin,str);
cout << "Encrypted: " << Cipher::Encrypt(str,key) << "\n";
cout << "Enter a string to decrypt: ";
getline(cin,str);
cout << "Encrypted: " << Cipher::Decrypt(str,key) << "\n";
return 0;
}
感謝您的幫助!
您忘記了兩種方法中的static
關鍵字:
static string Encrypt(string data, int key)
您需要使用類 Cipher 的對象在 main 中調用函數。
如果您不使用對象,則僅意味着這些函數未在 main 函數的范圍內定義。 您需要說明這些是 Cipher 類的一部分。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.