gpt4 book ai didi

c++ - 重载 >> 运算符给我运行时错误 C++

转载 作者:行者123 更新时间:2023-11-30 00:36:03 24 4
gpt4 key购买 nike

谁能帮帮我。下面是我要执行的代码。没有编译时错误,但是当控件转到字符串复制语句时程序崩溃。我尝试修复了将近一个小时,但仍然没有成功。

#include <iostream>

using namespace std;

class test
{
private:
char* name;
friend istream& operator >>(istream&, test&);
};

istream& operator >> (istream& is, test& t)
{
char c[20];

cout << "enter something";
is >> c;
strcpy(t.name, c);
return is;
}

int main()
{
test obj;
cin >> obj;

}

最佳答案

name调用时指针未初始化 strcpy ,这会给您的程序带来未定义的行为。

要避免此类问题,请使用 std::string而不是 C 字符串。更具体地说,以这种方式重新定义您的类:

#include <string> // Needed for std::string

class test
{
private:
std::string name;
friend istream& operator >>(istream&, test&);
};

为了使您的程序可以编译,您可以调整 operator >> 的重载这样:

istream& operator >> (istream& is, test& t)
{
cout << "enter something";
is >> t.name;
return is;
}

但是请注意,您不应该提示用户输入提取运算符内部的信息(即在 operator >> 的重载内部)。插入运算符只应该提取类型为 test 的对象来自输入流。

因此,提供一个完整的例子:

#include <iostream>
#include <string>

class test
{
private:
std::string name;
friend std::istream& operator >>(std::istream&, test&);
};

std::istream& operator >> (std::istream& is, test& t)
{
is >> t.name;
return is;
}

int main()
{
test obj;
std::cout << "enter something: ";
std::cin >> obj;
}

同时避免 using指令,例如:

using namespace std;

特别是如果在命名空间范围内,尤其是在 header 中(不是您的情况,但仍然如此)-它们往往会导致与生活在 std 中的实体发生名称冲突。命名空间。


编辑:

因为您似乎不被允许使用 std::string ,只有原始答案的第一句话仍然有效 - 以及关于您应该在哪里询问用户输入的部分。

所以这就是您可以编写的用于分配 t.name 的内容用户输入的字符串的拷贝:

t.name = strdup(c);

您需要包含 <cstring> strdup() 的标准标题:

#include <cstring>

我还建议初始化 name test 的构造函数中指向 null 的指针class - 它不会被隐式生成的默认构造函数初始化:

class test
{
test() : name(nullptr) { } // Use NULL instead of nullptr in C++03
private:
char* name;
friend istream& operator >> (istream&, test&);
};

所以在一个完整的程序中:

#include <iostream>
#include <cstring>

class test
{
public:
test() : name(nullptr) { }
private:
char* name;
friend std::istream& operator >>(std::istream&, test&);
};

std::istream& operator >> (std::istream& is, test& t)
{
char c[20];
is >> c;
t.name = strdup(c);
return is;
}

int main()
{
test obj;
std::cout << "enter something: ";
std::cin >> obj;
}

关于c++ - 重载 >> 运算符给我运行时错误 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17197134/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com