首页 > 解决方案 > 为什么我在 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 但什么都没有。只是空白存在。你能告诉我它为什么会发生以及如何解决它。干杯,伙计们。

标签: c++string

解决方案


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对象数组。


推荐阅读