我对自己的类和运算符 = 有疑问。当我尝试将 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;
}
在 C++ 中,代码只能出现在函数体内或变量初始化器中。这:
cow5 = cow6;
都不在里面,所以这是一个错误。您不能让代码“ float ”在函数之外。将它放在 main
中。
我是一名优秀的程序员,十分优秀!