为什么C++代码不起作用(strncpy_s)?

Why didn't work C++ code(strncpy_s)?

本文关键字:strncpy C++ 代码 不起作用 为什么      更新时间:2023-10-16

我是C 初学者。

当我研究C 类时,此示例代码不起作用。

此代码被namecard类构造函数中的strncpy_s((func中断。

我尝试调试,但找不到原因。

你能帮我吗?这是完整的源代码

祝您有美好的一天。

NameCard(char *name, char *phone, char *company, char *position)
{
    this->name = new char(strlen(name) + 1);
    this->phone = new char(strlen(phone) + 1);
    this->company = new char(strlen(company) + 1);
    this->position = new char(strlen(position) + 1);
    strncpy_s(this->name, strlen(name) + 1, name, strlen(name));
    strncpy_s(this->phone, strlen(phone) + 1, phone, strlen(phone));
    strncpy_s(this->company, strlen(company) + 1, company, strlen(company));
    strncpy_s(this->position, strlen(position) + 1, position, strlen(position));
}

您已滥用new操作员。

所有行,例如:

new char(strlen(name) + 1);

应替换为:

new char[strlen(name) + 1];

new char(X)为一个单个字符分配一个缓冲区,该缓冲区将填充其ASCII代码为X的字符。

new char[X]X chars分配缓冲区;这就是您想要的。

,但最好的是首先使用std::string

这是我将如何为C 17的代码重新编写。

#include <cstddef>
#include <iostream>
#include <memory>
#include <string>
using std::cout;
using std::endl;
using std::move;
using std::ostream;
using std::string;
class NameCard;
ostream& operator<<(ostream&, NameCard const&);
class NameCard
{
private:
  string _name;
  string _phone;
  string _company;
  string _position;
public:
  NameCard(string name, string phone, string company, string position)
    : _name{move(name)}
    , _phone{move(phone)}
    , _company{move(company)}
    , _position{move(position)}
  {
  }
  NameCard(NameCard const& c)
    : _name{c._name}
    , _phone{c._phone}
    , _company{c._company}
    , _position{c._position}
  {
  }
  ~NameCard()
  {
  }
  void print(ostream& o) const
  {
    o << _name << " " << _phone << " " << _company << " " << _position;
  }
};
ostream& operator<<(ostream& o, NameCard const& c)
{
  c.print(o);
  return o;
}
int main()
{
  auto James = NameCard{"James", "11231123", "la", "manager"};
  cout << James << endl;
  auto James2 = James;
  cout << James2 << endl;
  return EXIT_SUCCESS;
}