尝试定义一个函数,但我得到“变量或字段”function_A'声明为void“ [英] Trying to define a function, but I get "variable or field `function_A' declared void"

查看:231
本文介绍了尝试定义一个函数,但我得到“变量或字段”function_A'声明为void“的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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行)新类型不能在返回类型中定义。

(line 18) New types may not be defined in a return type.


推荐答案

您的问题的一部分是,在使用 Student c $ c> function_A 。要进行此操作,您需要

Part of your problem is you're using the type Student before it's defined by making it a parameter to function_A. To make this work you need to


  1. 添加转发声明 function_A

  2. 切换 function_A 接受指针或参考

  3. 移动 function_A 学生后。这是必要的,因此在访问之前定义会员课程

  4. 添加; class Student 定义
  5. 结束后
  1. Add a forward declaration function_A
  2. Switch function_A to take a pointer or reference
  3. Move function_A after Student. This is necessary so member courses is defined before it's accessed
  4. Add a ; after the end of the class Student definition

尝试以下



Try the following

class Student;
void function_A(Student& s);

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

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

这篇关于尝试定义一个函数,但我得到“变量或字段”function_A'声明为void“的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆