gpt4 book ai didi

c++ - "This declaration has no storage class or type specifier in C++"

转载 作者:太空宇宙 更新时间:2023-11-04 14:41:14 32 4
gpt4 key购买 nike

我对自己的类和运算符 = 有疑问。当我尝试将 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 中。

关于c++ - "This declaration has no storage class or type specifier in C++",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30357987/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com