【问题标题】:"This declaration has no storage class or type specifier in C++"“此声明在 C++ 中没有存储类或类型说明符”
【发布时间】: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++


【解决方案1】:

在 C++ 中,代码只能出现在函数体或变量初始化器中。这个:

cow5 = cow6;

两者都不在里面,所以这是一个错误。您不能让代码“浮动”在函数之外。把它放在main里面。

【讨论】:

    【解决方案2】:

    你不能在main()之外运行代码
    你只能定义变量,这就是为什么:

    Cow cow4
    

    作品

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多