我知道同样的问题有很多问题,但我没有发现任何与我的问题有关的问题。
我正在使用Xcode进行C ++项目,我收到以下错误:
Undefined symbols for architecture x86_64:
"Decrypt::printEncryptedString()", referenced from:
_main in main.o
"Decrypt::Decrypt()", referenced from:
_main in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
我的主要文件如下:
#include <iostream>
#include "Decrypt.hpp"
int main(int argc, const char * argv[]) {
Decrypt decryption = Decrypt();
decryption.printEncryptedString();
std::cout << "Hello, World!\n";
return 0;
}
我的标题:
#ifndef Decrypt_hpp
#define Decrypt_hpp
#include <stdio.h>
#endif /* Decrypt_hpp */
#include <string>
class Decrypt{
std::string toDecrypt;
std::string encrypted;
int keyLength; // key between 2 and 12
public:
Decrypt();
void printEncryptedString();
};
和.cpp文件:
#include <stdio.h>
#include <string>
#include <stdlib.h>
#include <iostream>
class Decrypt{
std::string toDecrypt;
std::string encrypted;
int keyLength;
public:
Decrypt(){
int i;
unsigned char ch;
FILE *fpIn;
fpIn = fopen("ctext.txt", "r");
i=0;
while (fscanf(fpIn, "%c", &ch) != EOF) {
/* avoid encrypting newline characters */
/* In a "real-world" implementation of the Vigenere cipher,
every ASCII character in the plaintext would be encrypted.
However, I want to avoid encrypting newlines here because
it makes recovering the plaintext slightly more difficult... */
/* ...and my goal is not to create "production-quality" code =) */
if (ch!='\n') {
i++;
encrypted += ch;
}
}
fclose(fpIn);
}
//void CalculateKeyLength(){}
void printEncryptedString(){
std::cout << encrypted << '\n';
}
};
我不明白导致错误的原因。有人能帮帮我吗?
答案 0 :(得分:1)
您可以在项目中多次定义Decrypt
类(否则包含头文件会有问题!),但是每个定义必须完全相同。< / p>
您有两个彼此不同的定义。一个人对其成员职能有内联定义;另一个没有。
这有未定义的行为,这里显然是因为你的编译器忽略了.cpp
中的定义,它将“看到”第二个。第二个定义包含您的成员函数定义,因此它们不会进入构建。
在.cpp
文件中,单独定义您的成员函数:
Decrypt::Decrypt()
{
int i;
unsigned char ch;
FILE *fpIn;
fpIn = fopen("ctext.txt", "r");
i=0;
while (fscanf(fpIn, "%c", &ch) != EOF) {
/* avoid encrypting newline characters */
/* In a "real-world" implementation of the Vigenere cipher,
every ASCII character in the plaintext would be encrypted.
However, I want to avoid encrypting newlines here because
it makes recovering the plaintext slightly more difficult... */
/* ...and my goal is not to create "production-quality" code =) */
if (ch!='\n') {
i++;
encrypted += ch;
}
}
fclose(fpIn);
}
void Decrypt::printEncryptedString()
{
std::cout << encrypted << '\n';
}
就像那样。不在第二个class
定义中。
C ++书中关于成员函数的章节将向您解释所有这些,等等。
另请注意,Decrypt.hpp
中的标题保护已在文件中间“关闭”而非结尾,这不是故意的?
答案 1 :(得分:-1)
您对Decrypt::printEncryptedString()
的定义与您的声明不同。在您的声明中,它被命名为void Decrypt::printEncryptedString
,您的定义定义了函数inline void Decrypt::printEncryptedString
。如果从函数定义中删除inline
关键字,则应编译。