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
在构造函数内部创建局部变量,而不是设置attribute的值a
。您可以a
在成员初始化器列表中设置in的值。
代码变成
#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
对象数组。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句