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

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

我是 C++ 初学者。

当我学习Class C++时,这个示例代码没有工作。

此代码被 NameCard class 构造函数中的 strncpy_s() 函数中断。

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

你能帮帮我吗? This is full source code

祝你有愉快的一天。

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));
}

以下是我将如何针对 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;
}

您误用了 new 运算符。

所有行如下:

new char(strlen(name) + 1);

应替换为:

new char[strlen(name) + 1];

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

的字符

new char[X]X 个字符分配缓冲区;这就是你想要的。

但最好首先使用 std::string