【发布时间】:2015-05-20 18:46:50
【问题描述】:
我自己的班级和运算符 = 有问题。当我尝试将 Cow 类的一个对象归因于某个函数之外的同一类的另一个对象时,我得到一条信息“此声明在 C++ 中没有存储类或类型说明符”。有什么问题?对不起我的英语。
#include "Header.h"
Cow cow5;
Cow cow6;
cow5 = cow6;
int main()
{
Cow cow1;
Cow cow2("cowa22", "hobby", 8);
Cow cow3 = cow2;
Cow cow4;
cow2.operator=(cow3);
}
#include "Header.h"
#include <string>
#include <iostream>
Cow::Cow()
{
strcpy_s(name, sizeof(char)*20, "unnamed");
hobby = nullptr;
weight = 0;
}
Cow::Cow(const char * nm, const char * ho, double wt)
{
strcpy_s(name, sizeof(char) * 20, nm);
hobby = new char[strlen(ho) + 1];
strcpy_s(hobby, sizeof(char)*(strlen(ho)+1), ho);
weight = wt;
}
Cow::Cow(const Cow & c)
{
strcpy_s(name, sizeof(char) * 20, c.name);
hobby = new char[strlen(c.hobby) + 1];
strcpy_s(hobby, sizeof(char)*(strlen(c.hobby) + 1), c.hobby);
weight = c.weight;
}
Cow::~Cow()
{
delete[] hobby;
}
Cow & Cow::operator=(const Cow & c)
{
if (&c == this)
return *this;
delete[] hobby;
strcpy_s(name, sizeof(char) * 20, c.name);
hobby = new char[strlen(c.hobby) + 1];
strcpy_s(hobby, sizeof(char)*(strlen(c.hobby) + 1), c.hobby);
weight = c.weight;
return *this;
}
void Cow::ShowCow() const
{
std::cout << "Name: " << name << std::endl
<< "Hobby: " << hobby << std::endl
<< "Weight: " << weight << std::endl;
}
【问题讨论】:
-
您粘贴了两次 .cpp 而不是 .h 和 .cpp
-
只是文体评论。不要在 C++ 中使用 char 数组,您使用
strcpy_s表示,请改用std::string。
标签: c++