繁体   English   中英

src \\ class-name.cpp中的C ++类错误

[英]C++ Class error in src\class-name.cpp

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

#include "Password.h"

Password::Password() //<-- error here 
{
    //ctor
}

Password::~Password() //<-- and here
{
    //dtor
}

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

你们知道什么地方可能出问题吗? 我已经搜索了几个小时,但找不到任何东西。 我正在使用代码块

用Password.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/中获得的一些代码。

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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM