大家好,这里是国中之林!
❥前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站。有兴趣的可以点点进去看看←
问题:
解答:
main.cpp
#include <iostream>
#include "Cow.h"
using namespace std;
int main()
{
Cow c1;
Cow c2("老母牛", "喝奶", 200);
Cow c3(c2);
c1 = c3;
c1.ShowCow();
cout << endl;
c2.ShowCow();
cout << endl;
c3.ShowCow();
cout << endl;
return 0;
}
Cow.h
#pragma once
#include <iostream>
using namespace std;
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;
};
Cow.cpp
#include "Cow.h"
Cow::Cow()
{
name[0] = '\0';
hobby = NULL;
weight = 0;
}
Cow::Cow(const char* nm, const char* ho, double wt)
{
if ((strcpy_s(name, 20, nm)))cout << "复制失败原字符太长!" << endl;
hobby = new char[strlen(ho)+1];
strcpy_s(hobby, strlen(ho) + 1, ho);
weight = wt;
}
Cow::Cow(const Cow&c)
{
strcpy_s(name,20, c.name);
hobby = new char[strlen(c.hobby) + 1];
strcpy_s(hobby, strlen(c.hobby) + 1, c.hobby);
weight = c.weight;
}
Cow::~Cow()
{
delete[] hobby;
}
Cow& Cow::operator=(const Cow& c)
{
if (this == &c)
{
return *this;
}
if (hobby)delete[] hobby;
strcpy_s(name, 20, c.name);
hobby = new char[strlen(c.hobby) + 1];
strcpy_s(hobby, strlen(c.hobby) + 1, c.hobby);
weight = c.weight;
return *this;
}
void Cow::ShowCow()const
{
if (hobby == NULL)
{
cout << "母牛的信息为空!" << endl;
return;
}
cout << "母牛的名字为:" << name << endl;
cout << "母牛的嗜好为:" << hobby << endl;
cout << "母牛的体重为:" << weight << endl;
}
运行结果:
考查点:
- 默认构造函数
- 自定义构造函数
- 拷贝构造函数
- 赋值构造函数
- 动态内存分配
注意:
-
strcpy_s
复制成功的返回值为0
-
strlen是得到字符串不带’\0’的长度,所以我们分配内存时需要加1
-
赋值构造函数返回的是引用用于连等
-
如果对象自己赋值自己就可以直接返回.如果原来指针不为空的需要清除
-
析构函数避免内存泄漏
2024年9月7日19:48:10
标签:const,name,Cow,weight,char,Plus,hobby,习题,Primer From: https://blog.csdn.net/qq_74047911/article/details/142000964