c++ - 为什么我在 C++ 中使用字符串时没有输出?
问题描述
class A{
private : string a[3];
public : A();
void ShowA();
}
A::A(){ string a[3] = {"aa","bb","cc"} }
void A::ShowA(){
for(int x=0;x<=2;x++){
cout<< a[x];
}
}
int main(){
A a;
a.ShowA();
return 0;
}
在这段代码中,我认为输出是 aabbcc 但什么都没有。只是空白存在。你能告诉我它为什么会发生以及如何解决它。干杯,伙计们。
解决方案
a
正如评论告诉您的那样,您正在构造函数中创建一个局部变量,而不是设置属性的值a
。您可以a
在成员初始值设定项列表中设置值。
代码变成
#include <iostream>
#include <string>
using namespace std;
class A {
private:
string a[3];
public:
A();
void ShowA();
};
A::A() : a{"aa"s, "bb"s, "cc"s} {}
void A::ShowA() {
for(int x = 0; x <= 2; x++) {
cout << a[x] << std::endl;
}
}
int main() {
A a;
a.ShowA();
return 0;
}
注意: "aa"、"bb" 和 "cc" 字符串后面的 's' 是字符串文字。在这种情况下实际上没有必要,因为编译器知道您正在创建一个std::string
对象数组。
推荐阅读
- python - 如何在 python 中查找/阅读有关方法和模块的文档?
- java - 推送通知未显示 - 为什么?
- php - Codeigniter 在 get from view 中传递参数导致 404 错误
- coldfusion - 无法从 Lucee Mail Listener 功能获得预期结果
- lisp - 如何返回特定列表
- node.js - 如何根据请求调用中间件并在 Node.js 中发送响应
- ios - 移动 Safari 中的文件上传和 EXIF
- c# - Linq:根据属性获取我所有的子对象
- php - 如何检查变量是否等于数组中的另一个变量
- c# - 迁移超过 5,000 个节点后发生以下异常: System.OutOfMemoryException