我的自己的类和operator =有问题。当我尝试将类属于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;
}
答案 0 :(得分:9)
在C ++中,代码只能出现在函数体或变量初始化器中。这样:
cow5 = cow6;
既不在里面,所以它是一个错误。你不能拥有代码&#34;浮动&#34;功能之外。把它放在main
内。
答案 1 :(得分:3)
您无法在main()
之外运行代码
您只能定义变量,这就是原因:
Cow cow4
作品