【发布时间】:2016-08-23 05:04:36
【问题描述】:
我正在阅读我的教科书并试图解决给读者的问题。
下面的代码是我的答案源文件中的函数定义。
我想将字符串的内容复制到另一个字符串。
我选择了函数 strncpy_s()。
但它不起作用。
Microsoft Visual Studio 说调试断言失败!
我不知道如何解决它。
牛.h
// 类声明
#include <iostream>
#ifndef COW_H_
#define COW_H_
class Cow {
char name[20];
char * hobby;
double weight;
public:
Cow();
Cow(const char * nm, const char * ho, double wt);
Cow(const Cow & c);
~Cow();
Cow & operator=(const Cow & c);
void ShowCow() const; // display all cow data
};
#endif
cow.cpp
// 类方法
Cow::Cow(const char * nm, const char * ho, double wt)
{
int len = std::strlen(nm);
strncpy_s(name, len, nm, len);
name[19] = '\0';
len = std::strlen(ho);
hobby = new char[len + 1];
strncpy_s(hobby, len, ho, len);
hobby[len] = '\0';
weight = wt;
}
Cow::Cow()
{
strncpy_s(name, 19, "no name", 19);
name[19] = '\0';
int len = std::strlen("no hobby");
hobby = new char[len + 1];
strncpy_s(hobby, len, "no hobby", len);
hobby[len] = '\0';
weight = 0.0;
}
Cow::Cow(const Cow & c)
{
int len = std::strlen(c.name);
strncpy_s(name, len, c.name, len);
name[19] = '\0';
len = std::strlen(c.hobby);
hobby = new char[len + 1];
strncpy_s(hobby, len, c.hobby, len);
hobby[len] = '\0';
weight = c.weight;
}
Cow::~Cow()
{
delete [] hobby;
}
Cow & Cow::operator=(const Cow & c)
{
if (this == &c)
return * this;
delete [] hobby;
int len = std::strlen(c.name);
strncpy_s(name, len, c.name, len);
name[19] = '\0';
len = std::strlen(c.hobby);
hobby = new char[len + 1];
strncpy_s(hobby, len, c.hobby, len);
hobby[len] = '\0';
weight = c.weight;
return * this;
}
void Cow::ShowCow() const
{
cout << name << ", " << hobby << ", " << weight << endl;
}
usecow.cpp
#include <iostream>
#include "cow.h"
int main()
{
Cow Japan;
Japan.ShowCow();
Cow America("Aspen", "Swim", 307.45);
America.ShowCow();
return 0;
}
【问题讨论】:
-
请在您使用
Cow类的地方添加代码。 -
您是否检查了您传递的参数与手册所说的需要什么?在一个地方您只传递
3参数,但在另一个地方您将4参数传递给strncpy_s。 -
@Ari0nhh 是的,我刚刚添加了usecow.cpp。
-
@Galik 我认为 strncpy_s() 在这些方面是一个重载函数。