[英]Access data member of a member function from one class to another class's member function
When I run the code it gives当我运行它给出的代码时
error: 'passArray' was not declared in this scope
cout << passArray[2];
^~~~~~~~~
So I want to access that character array and modify the array.所以我想访问那个字符数组并修改数组。 For example user input is
last
(in string p
) then it will be converted into character array( passArray
).例如,用户输入是
last
(在string p
中),那么它将被转换为字符数组( passArray
)。 Then void convert()
function should modify passArray[0]
which is letter l
to letter f
and give the output as fast
.然后
void convert()
function 应该修改passArray[0]
,它是字母l
到字母f
并给 output as fast
。 Like this I want to modify many letters at once as l to f
, a to e
, s to l
, t to t
final word would be felt
from the word last
.像这样我想一次修改许多字母,因为
l to f
, a to e
, s to l
, t to t
最终单词会从单词last
中felt
。
Here is the code:这是代码:
#include <bits/stdc++.h>
using namespace std;
class PasswordConverter {
protected:
string p;
int length;
public:
void getPassword() {
cout << "Enter password to convert into strong one: ";
cin >> p;
length = p.length();
}
void show() {
cout << p << endl;
cout << length << endl;
}
};
class strToarr : public PasswordConverter {
public:
void typeCast() {
char passArray[length + 1];
strcpy(passArray, p.c_str());
}
};
class Convert : public strToarr {
public:
void convert() {
cout << passArray[2];
}
};
int main(int argc, char const *argv[]) {
Convert strong;
strong.getPassword();
strong.show();
strong.typeCast();
strong.convert();
return 0;
}
I've tried to fix and simplify the code.我试图修复和简化代码。 I believe there is no need for any classes, just keep it simple with ordinary functions.
我相信不需要任何类,只需使用普通函数保持简单即可。
Also please not that std::string
already has operator[]
so the extra array is not necessary to edit the string but I kept it there if you need it.也请不要
std::string
已经有operator[]
所以额外的数组不是编辑字符串所必需的,但如果你需要它我把它保留在那里。
// Do NOT use this, don't be lazy and include the proper headers
//#include <bits/stdc++.h>
#include <iostream>
#include <string>
#include <vector>
// Also do not use this, at least not in headers
//using namespace std;
std::string getPassword() {
std::string p;
std::cout << "Enter password to convert into strong one: ";
std::cin >> p;
return p;
}
void show_password(const std::string& password) {
// Do not use 'endl' for newlines, sadly it also flushes the buffer
// making it slow.
std::cout << password << '\n';
std::cout << password.size() << '\n';
}
std::vector<char> typeCast(const std::string& p) {
auto begin = p.c_str();
std::vector<char> p_array{begin,begin+p.size()+1};
return p_array;
}
void convert(const std::vector<char>& passArray) {
std::cout << passArray[2];
}
int main(int argc, char const *argv[]) {
auto pass = getPassword();
show_password(pass);
auto pass_array = typeCast(pass);
convert(pass_array);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.