简体   繁体   English

此声明在 C++ 中没有存储类或类型说明符

[英]This declaration has no storage class or type specifier in C++

I have multiple classes in my program.我的程序中有多个类。

A) When I create an object of a class in another class I am getting no error but when I use the object to call a function I get the above error. A)当我在另一个类中创建一个类的对象时,我没有收到任何错误,但是当我使用该对象调用一个函数时,我收到了上述错误。

B)Also if I create an object of another class and call a function using that in the constructor of my class then I get no error like this. B)另外,如果我创建另一个类的对象并在我的类的构造函数中使用它调用一个函数,那么我不会得到这样的错误。

C) Cout function does not work in the body of the class except when I put it any function C) Cout 函数在类的主体中不起作用,除非我把它放在任何函数中

D) The main class is able to do all of these and I am not getting any error. D)主类能够完成所有这些,我没有收到任何错误。

It would be great to hear back soon.很高兴能很快收到回复。 Thank you in advance.先感谢您。

Following is the code : These are two classes in my cpp.以下是代码:这是我的 cpp 中的两个类。 I am facing no problems except using object after creating it.除了在创建对象后使用对象外,我没有遇到任何问题。 the code is too huge too be posted.代码太大了,不贴了。 Everything can be done in main but not in other classes why?一切都可以在 main 中完成,但不能在其他类中完成,为什么?

 #include <iostream>
 #include <fstream>
 #include <iomanip>
 #include <string>
 #include <cstdlib> 
 #include <vector>
 #include <map>
 using namespace std;
 class Message
 {
    public:
    void check(string side)
   {
       if(side!="B"&&side!="S")
       {
           cout<<"Side should be either Buy (B) or Sell (S)"<<endl;;
       }
   }


};

class Orderbook
{
    public:
      string side;
      Orderbook()      //No Error if I define inside constructor
      Message m;       //No Error while declaring
      m.check(side);   //Error when I write m. or m->
};

This is a mistake:这是个错误:

m.check(side);

That code has to go inside a function.该代码必须进入函数内部。 Your class definition can only contain declarations and functions.您的类定义只能包含声明和函数。

Classes don't "run", they provide a blueprint for how to make an object.类不会“运行”,它们提供了如何创建对象的蓝图。

The line Message m;Message m; means that an Orderbook will contain Message called m , if you later create an Orderbook .意味着Orderbook将包含名为m Message ,如果您稍后创建Orderbook

Calling m.check(side), meaning you are running actual code, but you can't run code outside main() - you can only define variables.调用 m.check(side),意味着您正在运行实际代码,但您不能在 main() 之外运行代码 - 您只能定义变量。 In C++, code can only appear inside function bodies or in variable initializes.在 C++ 中,代码只能出现在函数体内或变量初始化中。

You can declare an object of a class in another Class,that's possible but you cant initialize that object.您可以在另一个类中声明一个类的对象,这是可能的,但您不能初始化该对象。 For that you need to do something like this :--> (inside main)为此,您需要执行以下操作:-->(在 main 中)

Orderbook o1;
o1.m.check(side)

but that would be unnecessary.但这将是不必要的。 Keeping things short :-保持简短:-

You can't call functions inside a Class您不能在类中调用函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM