我正在学习 C++,目前我正在使用字符串和指针。
我正在关注一本练习册,针对其中一个问题,我创建了以下内容:
#include <iostream>
#include <string>
using namespace std;
int main(void){
string * firstName=nullptr;
string * lastName=nullptr;
string * displayName=nullptr;
cout << "Enter your first name: " << endl;
getline(cin,*firstName);
cout << "Enter your last name: " << endl;
getline(cin,*lastName);
displayName=new string;
*displayName= *lastName + ", " + *firstName;
cout << "Here's the information in a single string: " << displayName;
cin.get();
return 0;
}
为了使用更多的指针,我尝试将它与字符串混合在一起,并因此使解决方案更加复杂。当我运行它时,我得到一个“未处理的异常:访问冲突读取位置 xxxxxxxxx”。
是否有人可以通过仍然使用指针和字符串而不是 char 数组来提出解决方案(我已经知道该怎么做)?
最佳答案
这是因为您在使用对象之前没有分配您的对象:
string * firstName = new string();
//...
delete firstName;
值得补充的是,在这种情况下使用指针毫无意义:标准 C++ 库中的字符串对象从堆中为字符串分配数据;无论如何,字符串通常不过是一对指针。
关于C++ 字符串和指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9554812/