【发布时间】:2017-08-02 18:18:17
【问题描述】:
我正在自学 C++,并且正在完成一本教程书中的练习。在当前问题中,我应该将一个空指针传递给一个用于触发分配姓氏提示的姓氏参数的方法。
我的问题是:
- 引发异常。
- 如果我以避免异常的方式进行分配,则不会在方法之外返回。
- 根据我当前的搜索结果,似乎需要双指针或引用。但是,我需要为方法使用指针参数(我使用引用参数作为另一个练习),并且文本中还没有介绍双指针(所以我觉得这是作弊/错过了课程的重点)。
如何将空指针赋值给字符串,以便在不使用引用或双指针的情况下将其保留在方法之外?
当前代码:
#include <iostream>
#include <string>
using namespace std;
void getNameByPointer(string* firstName, string* lastName)
{
cout << "Please enter your first name: ";
cin >> *firstName;
// Check for null.
// Only request last name IF null, as per the book exercise statement.
if (!lastName)
{
string tempLastName;
cout << "Please enter your last name: ";
cin >> tempLastName;
// Note: All assignment methods below fail in some way if lastName is null.
// I cannot find a way to assign to a null pointer that carries out
// of the method without using a double pointer or pointer
// reference, which are not yet introduced in the book.
// (1) Throws exception 'Read Access violations': std::_String_alloc<std::_String_base_types<char,std::allocator<char> > >::_Myres(...) returned 0x18.
// *lastName = tempLastName;
// (2) This assignment is limited to the method scope.
// lastName = &tempLastName;
// (3) This assignment is limited to the method scope.
// lastName = new string(tempLastName);
}
}
int main()
{
string firstName;
string lastName;
getNameByPointer(&firstName, &lastName);
cout << "Your name is " << firstName << " " << lastName << '\n';
cout << "Calling method with NULL...\n";
string firstName1;
// Null pointer
string *lastName1 = nullptr;
getNameByPointer(&firstName1, lastName1);
if(lastName1)
{
cout << "Your name is " << firstName1 << " " << *lastName1 << '\n';
}
else
{
cout << "Your name is " << firstName1 << '\n';
}
}
编辑:为了更好地澄清我是否误读了问题,或者更好地传达我的限制,问题如下:
练习 3
修改您为练习 1 编写的程序,使其不再提示用户输入姓氏,而是仅在调用者为姓氏传入 NULL 指针时才这样做。
(习题 1 已经解出,但作为习题 3 的基础。)
练习 1
编写一个函数,提示用户输入他或她的名字和姓氏,作为两个单独的值。此函数应通过传递给函数的附加指针(或引用)参数将这两个值返回给调用者。尝试先使用指针,然后使用引用。
(对于练习 3,对引用函数进行了类似的解决方案,仅检查变量是否为空,因为无法在引用参数中检查 NULL。)
【问题讨论】:
-
您确定要使用指针吗?您可以通过引用传递字符串,如果它们为空,您可以使用
empty()进行检查。 -
我已经通过引用作为练习的另一部分。所以我的问题是关于实施而不是战略。或者他们在练习中所要求的可能由于范围可变的问题在技术上是不可行的?
-
是否允许接受对指针的引用?喜欢:
void getNameByPointer(string* firstName, string*& lastName)? -
使用单独的函数。经验法则是,如果您有一个“可选”参数完全切断了一半的函数处理,则该函数做的太多了。
-
向我们展示练习的全文。也许你错过了一些东西。或者我们可以向您展示解决问题的更好方法。