C++ srcclass-name.cpp 中的类错误

C++ Class error in srcclass-name.cpp

本文关键字:错误 srcclass-name cpp C++      更新时间:2023-10-16

在C++已经编程了将近一年了。但是我一直避免上课(是的,我知道,坏主意)。我的.cpp文件有问题

#include "Password.h"
Password::Password() //<-- error here 
{
    //ctor
}
Password::~Password() //<-- and here
{
    //dtor
}

它会给我一个错误,这两个提到的地方。错误是"错误:'密码::P assword()'的原型与类'密码'中的任何内容都不匹配"我试图注释掉所有内容,没有它,程序似乎运行良好。

你们知道可能出了什么问题吗?我已经找了几个小时了,什么也找不到。我正在使用代码块

使用密码编辑.h

#ifndef PASSWORD_H
#define PASSWORD_H
#include <iostream>
#include <string>
#include <conio.h>
using namespace std;
class Password
{
       protected: /* A password should be protected, right? */
        string password; /* The string to store the password */
        string input; /* The string to store the input */

public:
    /* Constructor, pass a string to it (the actual password) */
    Password (string pass) {this->password = pass;}
    void Input () /* Get the password from the user */
    {
        while (true) /* Infinite loop, exited when RETURN is pressed */
        {
            char temp;
            temp= getch(); /* Get the current character of the password */
            //getline(cin, temp);
            if (cin.get() == 'n') {
            return;
            }
            /* Exit the function */
            input += temp;
            cout << '*'; /* Print a star */
        }
    }
    bool Compare () /* Check if the input is the same as the password */
    {
        if (password.length() != input.length()) /* If they aren't the same length */
            return false; /* Then they obviously aren't the same! */
        for (unsigned int i = 0; i <= input.length(); i++)
        { /* Loop through the strings */
            if (password[i] != input[i])
                return false; /* If anything is not a match, then they are not the same */
        }
        return true; /* If all checks were passed, then they are the same */
    }
};
#endif // PASSWORD_H

这是我从 http://www.dreamincode.net/forums/topic/59437-how-to-make-a-password-show-as-stars/Credits那里得到的一些代码。

>Password::Password() { ... }将定义一个已经声明的函数。

为此,

  1. 该函数必须已经声明(在 Passwordclass 声明中)--
      并且
    • 应该用相同的签名声明,并且
  2. 函数不得已定义 - 仅声明;
    • 否则,您将定义一个函数两次,编译器将抱怨。

.h文件中,您有:

Password (string pass) {this->password = pass;}

在这里,您可以注意到两个问题:

  1. 此构造函数的签名不同于 cpp 文件中定义的构造函数的签名;构造函数Password()不存在任何地方,因此无法在 cpp 文件中定义!
  2. 构造函数已经定义,因此如果将 cpp 文件中构造函数的签名固定为包含 string pass ,您将看到一个新错误。

让您的 CPP 代码按原样工作

您的password.h应更改其class Password声明,以包括:

// Password.h
class Password {
public:
    Password(); // default ctor ; declared, not defined
    ~Password(); // default dtor ; declared, not defined
}

使 cpp 文件中的Password::Password具有与头文件相同的行为

更改头文件,以便:

// password.h
...
Password (string pass); // only declared
...

,然后更改 CPP 文件:

Password::Password(std::string pass) { // ctor
}