我完全是 C++ 的初学者,到目前为止,在学校里我们只学习和使用过 Java。我们今年的第一个项目是创建一个凯撒密码,但我们必须使用我们教授提供的头文件。在这一点上,我只是试图在编码加密和解密方法之前移动字母并证明我的概念。关于我做错了什么以及为什么这段代码没有编译的任何帮助都会很棒。
这是我们的头文件,我们根本不允许对此文件进行任何更改:
// include file for Caesar cipher code
//
#ifndef CAESAR_H
#define CAESAR_H
#include <string>
class Caesar {
private:
//pointers used to refer to the standard alphabet array and the Caesar shift array
char* std_alphabet;
char* c_alphabet;
public:
// The constructor . . .
// create the two arrays with the c_alphabet array contents representing the std_alphabet
// characters shifted by a value of the shift parameter
Caesar(int shift = 0);
// encrypt a message. Returns count of characters processed
// first string is message, second is encrypted string
int encrypt(const std::string& message, std::string& emessage);
// decrypt a message. Returns count of characters processed
// first string is encrypted string, second is decrypted string
int decrypt(const std::string& message, std::string& dmessage);
//delete any memory resources used by the class
~Caesar();
}; // end of class . . .
#endif
这是我的 .cpp 文件,我目前只是在尝试在数组中移动我的字母表,但我不明白为什么我的头文件使用指针或者我是否正确创建了我的数组(我能够让这个概念在单独的文件中工作但不使用头文件)。在进行任何编码之前,我只是尝试打印这些行以确保它能正常工作:
#ifndef CAESAR_C
#define CAESAR_C
#include <string>
#include <iostream>
#include "Caesar.h"
using namespace std;
int shift, i, k;
char letter = 'a';
Caesar::Caesar(const int n) {
shift = n;
std_alphabet[26];
c_alphabet[26];
for (i = 0; i < 26; i++) {
std_alphabet[i] = letter;
letter++;
}
for (i = 0; i < 26; i++) {
cout << std_alphabet[i] << " ";
}
cout << endl;
for (i = 0; i < 26; i++) {
k = (i + shift) % 26;
c_alphabet[i] = std_alphabet[k];
}
for (i = 0; i < 26; i++) {
cout << c_alphabet[i] << " ";
}
};
#endif
这是我的测试文件,我真的不知道如何正确启动 Caesar 对象。就像我说的那样,我是 C++ 的完全初学者,非常感谢任何指示:
#include <string>
#include <iostream>
#include "Caesar.h"
using namespace std;
int main() {
Caesar* test = new Caesar(5);
cout << test;
system("PAUSE");
return 0;
};
最佳答案
如果我的回答含糊不清,请不要介意,因为我对参与 stackoverflow 还很陌生
在问这个问题之前,您似乎没有对这个问题做太多研究,甚至没有尝试自己找出解决方案。但无论如何,我会尽量对你有所帮助。
先做这些(我猜已经知道这些事情):
- 当然,首先,将头文件和 cpp 文件分别保存为 Caesar.h 和 Caesar.cpp,test.cpp 可能是测试文件。
- 然后在您的测试文件中包含 header “stdlib.h”,因为您正在使用函数 system()。
- 然后使用命令 g++ Caesar.cpp test.cpp -o test 编译您的程序并运行它。
现在,您的代码的主要问题在 cout << test; 行。 您必须首先为类“Caesar”重载运算符“<<”,这将打印私有(private)成员变量 std_alphabet 和 c_alphabet 中的值。我建议你浏览一下这个页面http://www.geeksforgeeks.org/overloading-stream-insertion-operators-c/
此外,“Ceasar”类的设计策略也不尽如人意。我的意思是“Caesar.cpp”中的变量“shift”应该是类“Caesar”的私有(private)成员变量,这更有意义。无论如何,这些只是 OOP 问题。
还有一件事是构造函数包含两行:std_alphabet[26] 和 c_alphabet[26]
老实说,我不知道那个奇怪的语法是什么,但它以某种方式被编译到我的系统中。但这就是导致程序在运行时崩溃的原因。因此,我建议将这两行替换为
std_alphabet = new char[26]; 并类似地替换为 c_alphabet/strong>.
最后,您只需在文件“Ceasar.h”中定义函数 encrypt() 和 decrypt()。 cpp',我希望你能做那么多,因为这是你的任务 :D
祝你好运!!!
关于c++ - Caesar Cipher C++(数组和指针),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46102748/