【问题标题】:Trying to define a function, but I get "variable or field `function_A' declared void"试图定义一个函数,但我得到“变量或字段‘function_A’声明为无效”
【发布时间】:2011-04-29 00:06:06
【问题描述】:
#include <cstdio>
#include <cstdlib>
#include <iostream>

using namespace std;

class Student;
void function_A(Student& s)

class Student { 
   void function_B() {
        ::function_A(*this);
   }
   int courses;
};

void function_A(Student& s)
{ // line 18 (where error is occurring)
     s.courses = 1;
}

int main()
{
    Student s;
    s.function_B();
    return 0;
}

我得到的错误如下:

(第 18 行)新类型可能未在返回类型中定义。

【问题讨论】:

  • +1。这比看起来更棘手。我编辑了标题以使其更具描述性。
  • 欢迎来到 StackOverflow!很好的问题,但请不要在人们仍在回答您的问题时更改您的代码。

标签: c++


【解决方案1】:

您的部分问题是您在通过将其作为function_A 的参数来定义它之前使用类型Student。要完成这项工作,您需要

  1. 添加前向声明function_A
  2. 切换 function_A 以获取指针或引用
  3. 在Student 之后移动function_A。这是必要的,因此成员 courses 在访问之前就已定义
  4. 在class Student 定义的末尾添加;

试试下面的

class Student;
void function_A(Student& s);

class Student { 
   // All of the student code
};

void function_A(Student& s) {
  s.courses = 1;
}

【讨论】:

  • 最重要的是,在类定义之后需要一个;。
  • @AndreyT 没有注意到这一点。更新了答案。谢谢!
【解决方案2】:

你必须转发声明Student。

地点

 class Student;

在function_A之前。

【讨论】:

  • 前向声明也是不够的,因为 Student 对象是按值传递的,而 function_A 引用了 Student 类的成员变量。
猜你喜欢
  • 1970-01-01
  • 2017-12-09
  • 2021-12-20
  • 1970-01-01
  • 2013-11-25
  • 2017-04-19
  • 1970-01-01
  • 1970-01-01
  • 2014-05-08
相关资源
最近更新 更多