C++类中部分方法无法访问类成员属性,部分方法可正常访问
问题原因与解决方案
核心问题:变量遮蔽
你代码里的问题出在变量遮蔽(Name Shadowing):
- 在
isMatch函数内部,你定义了局部变量TypePattern pattern(s),它和类Solution的成员变量pattern重名了。 - 当你在
isMatch里直接调用pattern.printPattern(),访问的是这个局部初始化好的对象,所以输出正确。 - 但
increaseOccurrencies()函数里调用的pattern,是类的成员变量——这个成员变量只执行了默认构造,没有被s初始化,所以输出空值。
可行解决方案
方案1:修改局部变量名,赋值给成员变量
把isMatch里的局部变量改名避免遮蔽,再同步值给类成员:
bool isMatch(string s, string p){ TypeText localText(s); TypePattern localPattern(s); // 将局部对象赋值给类成员 this->text = localText; this->pattern = localPattern; localPattern.printPattern(); // 正常输出 increaseOccurrencies(); // 现在调用的是初始化后的成员变量 }
方案2:直接初始化类成员变量
不要定义局部变量,直接给类的成员变量赋值初始化:
bool isMatch(string s, string p){ this->text = TypeText(s); this->pattern = TypePattern(s); this->pattern.printPattern(); // 正常输出 increaseOccurrencies(); // 使用初始化后的成员变量 }
方案3:给函数传参,直接使用局部对象
修改increaseOccurrencies,让它接收局部对象的引用,无需依赖类成员:
// 类内部的函数声明修改为: bool increaseOccurrencies(TypePattern& pattern, TypeText& text){ pattern.printPattern(); // 这里可以直接用传入的text和pattern } // isMatch里调用: bool isMatch(string s, string p){ TypeText text(s); TypePattern pattern(s); pattern.printPattern(); increaseOccurrencies(pattern, text); // 传入初始化好的对象 }
内容的提问来源于stack exchange,提问作者John Smith
相关产品推荐
相关产品推荐

