[英]“This declaration has no storage class or type specifier in C++”
I have problem with my own class and operator =. 我自己的班级和运算子=有问题。 When I try to attribute to one object of class Cow another one of the same class outside of some function I get an information "This declaration has no storage class or type specifier in C++". 当我尝试将某个类的一个对象的属性赋给Cow某个功能之外的同一类的另一个对象时,我得到一条信息“此声明在C ++中没有存储类或类型说明符”。 What's the problem? 有什么问题? I'm sorry for my english. 对不起我的英语。
#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;
}
In C++, code can only appear inside function bodies or in variable initialisers. 在C ++中,代码只能出现在函数体内或变量初始化器中。 This: 这个:
cow5 = cow6;
is inside neither, so it's an error. 都在里面,所以这是一个错误。 You cannot have code "floating" outside of a function. 您不能在函数外部使用“浮动”代码。 Put it inside main
. 把它放在main
里面。
You can't run code outside main()
您不能在main()
之外运行代码
You can only define variables, that's why: 您只能定义变量,因此:
Cow cow4
Works 作品
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.