【发布时间】:2015-02-22 02:38:36
【问题描述】:
我是 C++ 新手,所以如果这是一个愚蠢的问题,请多多包涵。
下面的方法似乎创建了一个名为reversePhrase但没有初始值的字符串,然后使用它phrase.evalPalindrome(reversePhrase):
void testForPalindrome(string origPhrase)
{
string reversePhrase;
bool isPalindrome;
Palindrome phrase(origPhrase);
if (phrase.evalPalindrome(reversePhrase))
{
cout << "This phrase IS a palindrome!" << endl;
}
else
{
cout << "This phrase is NOT a palindrome." << endl;
}
cout << "Original phrase: " << origPhrase << endl;
cout << "Reverse phrase: " << reversePhrase << endl << endl;
}
在 java 中,这将创建一个空指针异常。但是我分析了正在调用的方法,它看起来像是接受字符串的地址。
bool Palindrome::evalPalindrome (string& reversePhrase)
{
// code
}
但我不明白这是如何工作的。最初的string reversePhrase; 是否只是将内存分配给reversePhrase?如果是,那么调用函数如何能够打印出从另一个函数修改的reversePhrase(代码未显示,但它是从另一个函数修改的)。
用这种方式编写代码似乎很难阅读。
【问题讨论】:
-
String reversePhase = new String();在 Java 中等于string *reversePhase = new string();在 C++ 中。在 Java 中,reversePhase在这种情况下是指针,所以如果你不给它分配任何东西,你会得到一个异常。