C++ 为什么类成员变量在全局类数组构造函数执行后部分工作?

C++ 为什么类成员变量在全局类数组构造函数执行后部分工作?,c++,C++,我声明并定义一个全局类数组testarrs[]={{“1”},{“2”} 我确保数组中每个元素的构造函数都已执行。 我的测试类声明在文件Test.h中: #pragma once #include <iostream> #include <string> using namespace std; class Test { public: string from, suffix; Test(string s); }; 为什么from成员变量为空?我已将

我声明并定义一个全局类数组
testarrs[]={{“1”},{“2”}
我确保数组中每个元素的构造函数都已执行。
我的测试类声明在文件Test.h中:

#pragma once
#include <iostream>
#include <string>

using namespace std;

class Test {
public:
    string from, suffix;
    Test(string s);
};

为什么
from
成员变量为空?我已将其指定给“abc”。

您的方法参数正在隐藏实际的成员变量“from”。将代码更改为:

#include "test.h"
Test::Test(string variable_not_called_from) {
    from = "abc";
    suffix = "123";
    cout << "Test constructor from = " << from << " suffix = " << suffix << endl;// diagnostic
}
#包括“test.h”
Test::Test(字符串变量_not_称为_from){
from=“abc”;
后缀=“123”;
库特
#include "test.h"
Test arrs[] ={ {"1"}, {"2"} };

int main() {
    cout <<" cons[0] test from: " << arrs[0].from << endl;
    cout <<" cons[0] test suffix: " << arrs[0].suffix << endl;
    cout <<" cons[1] test from: " << arrs[1].from << endl;
    cout <<" cons[1] test suffix: " << arrs[1].suffix << endl;
}
Test constructor from = abc suffix = 123
Test constructor from = abc suffix = 123
cons[0] test from:
cons[0] test suffix: 123
cons[1] test from:
cons[1] test suffix: 123
#include "test.h"
Test::Test(string variable_not_called_from) {
    from = "abc";
    suffix = "123";
    cout << "Test constructor from = " << from << " suffix = " << suffix << endl;// diagnostic
}