“缺少类型说明符"构造函数声明错误 [英] "missing type specifier" error on constructor declaration

查看:51
本文介绍了“缺少类型说明符"构造函数声明错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 2 个不同的文件中有 2 个类:

I have 2 classes in 2 different files:

RegMatrix.h:

RegMatrix.h:

#ifndef _RM_H
#define _RM_H
#include "SparseMatrix.h"
...
class RegMatrix{
    ...
    RegMatrix(const SparseMatrix &s){...}   //ctor
    ...
};
#endif

稀疏矩阵.h:

#ifndef _SM_H
#define _SM_H
#include "RegMatrix.h"
...
class SparseMatrix{
    ...
    SparseMatrix(const RegMatrix &r){...}   //ctor
    ...
};
#endif

在构造函数行上,我收到错误:

On the constructor lines I get the errors:

错误 C4430:缺少类型说明符 - 假定为 int.

error C4430: missing type specifier - int assumed.

错误 C2143:语法错误:在&"之前缺少,"

error C2143: syntax error : missing ',' before '&'

但是当我添加类声明时

class SparseMatrix;

在 RegMatrix.h 文件和

in the RegMatrix.h file and

class RegMatrix;

在 SparseMatrix.h 文件中它工作正常.我的问题是,如果我有包含,为什么需要它?10 倍.

in the SparseMatrix.h file it works fine. My question is why is it needed if i have the includes? 10x.

推荐答案

你不能有循环 #includes(一个文件 #includes 另一个 #includes 第一个文件).向前声明其中一个类而不是 #include 将打破链并允许它工作.声明类名允许您使用该名称而无需了解类的内部位.

You can't have circular #includes (one file #includes another which #includes the first file). Forward declaring one of the classes instead of the #include will break the chain and allow it to work. Declaring the class name allows you to use the name without having to know about the internal bits of the class.

顺便说一句,对循环#includes 的渴望是一种设计味道.或许你可以创建一个接口来代替这两个类?这样他们就不必相互依赖了.

BTW, the desire for circular #includes is a design smell. Perhaps you could create an interface that the two classes can depend on instead? Then they won't have to mutually depend on each other.

这篇关于“缺少类型说明符"构造函数声明错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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