-4

c++中的面向对象编程

我在 C++ 中学习 oop,不能使用 oop 来解决这个问题。oop可能不是最好的解决方案,但我想要它。这个问题可能很简单,但我无法解决它显示

**error: cannot convert '<brace-enclosed initializer list>' to 'char' in assignment**
#include <iostream>
#include<ctype.h>
#include<time.h>
#include<stdlib.h>
#include<string>
#include<string.h>
#include<ctime>
using namespace std;
class passwordGenerate{
private:
char letters[56];
int length;
char password[100];
public:
    passwordGenerate();
    void setLength(int);
    void setPassword(char p[]);
    void displayPassword();
};
passwordGenerate::passwordGenerate(){
  letters[56] = {'a','b','c','d','e',
                    'f','g','h','i','j',
                    'k','l','m','n','o',
                    'p','q','r','s','t',
                    'u','v','w','x','y','z',
                    '0','1','2','3','4','5','6','7','8','9',
                    '.','+','-','*','/',
                     '=','_',')','(','&',
                     '%','$','#','@','!',
                     '~',',','>','?','<'};
//it works when char letters[56] is given but does not work in this way.
}
void passwordGenerate::setLength(int l){
length = l;
}
void passwordGenerate::displayPassword(){
strcpy(password," ");
int random;
srand(time(0));
 for(int x =0 ;x<length;x++){
        random = rand()%55;
        password[x] = letters[random];
 }
 for(int i=0;i<length;i++){
 cout<<password[i];
 }
}


int main()
{
    passwordGenerate firstPassword;
    int length;
    cout<<"enter the length for password : ";
    cin>>length;
    firstPassword.setLength(length);
    firstPassword.displayPassword();


    return 0;
}
4

1 回答 1

1

[]这两者有本质区别

int x[5] = {1,2,3,4,5};
//    ^-----------------   size of the array

x[2] = 42;
//^---------------------   index of array element

所以当你写

letters[56] = {'a',' .....

然后这是第一次越界访问数组(它有 56 个元素,letters[56]是第 57 个元素)。而且您不能分配{'a',...给单个char(元素类型)。

为了解决这个问题,我建议您std::string改用类内初始化程序:

struct foo {
     std::string letters{"abcdefghijklmnop...."};
};

最后但同样重要的是,我建议命名该成员alphabet而不是letters,因为它不仅仅是字母。

于 2020-07-06T10:34:38.507 回答