如何修复和编译此C 程序

How to fix and compile this C++ program

本文关键字:程序 编译 何修复      更新时间:2023-10-16

在nestclassdef.h中,我已经写了这样的代码

  class A{
    public:
     class B{
         public:
           void BTest();
     };
 };
   class B{
   };

然后在nestclassdef.cpp中我正在编写像这样的代码

      #include "nestClassDef.h"
      #include<iostream>
      void A::B::BTest(){
        cout<<"Hello World!";
     }
    int main(){
      A a;
      A.B b;
      b.BTest();
    } 

但是当我编译上述代码

       g++ -o nestClassDef nestClassDef.cpp

我遇到这样的错误: -

      nestClassDef.cpp: In member function ‘void A::B::BTest()’:
      nestClassDef.cpp:5: error: ‘cout’ was not declared in this scope
      nestClassDef.cpp: In function ‘int main()’:
      nestClassDef.cpp:10: error: expected unqualified-id before ‘.’ token
      nestClassDef.cpp:11: error: ‘b’ was not declared in this scope 

我不知所措地解决此问题。值得庆幸的是,共享的任何理解。

对于cout错误:它在std名称空间中,因此请使用std::cout

对于第二个错误:B不是A's成员,它是嵌套类型,因此您必须使用A::B b;

  nestClassDef.cpp: In member function ‘void A::B::BTest()’:
  nestClassDef.cpp:5: error: ‘cout’ was not declared in this scope

使用std::cout代替cout,或添加using namespace std;(可能是在您的#include语句之后)。

  nestClassDef.cpp: In function ‘int main()’:
  nestClassDef.cpp:10: error: expected unqualified-id before ‘.’ token
  nestClassDef.cpp:11: error: ‘b’ was not declared in this scope 

使用A::B代替A.B

  1. 添加using namespace std;或使用std::cout代替cout
  2. 使用A::B不是A.B。点运算符用于对象或结构/工会。