【问题标题】:X does not name a type in c++ [duplicate]X没有在c ++中命名类型[重复]
【发布时间】:2020-11-21 22:07:03
【问题描述】:

我正在学习 c++,特别是,我正在学习继承。我编写了以下代码,我想打印protected_stuff 的内容,这是一个在MainClass 中的protected 访问说明符中定义的变量。

这是我的代码:

  • inheritance.cpp
#include<iostream>
#include"MainClass.h"
#include"DerivedClass.h"


int main(){

    DerivedClass a;
    a.func();
    return 0;
}
  • DerivedClass.h
#ifndef DERIVEDCLASS

#define DERIVEDCLASS

class DerivedClass: public MainClass{
private:
    int val;
protected:
    int val2;
public:
    int val3;

    void func(void){
        std::cout<<protected_stuff;
    }

};

#endif
  • MainClass.h
#ifndef MAINCLASS
#define MAINCLASS


class MainClass{

private:
    int value;
    char charecter;

    value= 10;
    charecter='a';

protected:
    int protected_stuff;
    protected_stuff = 2;


public:
    int public_stuff;
    public_stuff = 3;

};

#endif

当我尝试运行 g++ -I . inheritance.cpp 时,出现以下错误:

In file included from inheritance.cpp:2:
MainClass.h:11:2: error: 'value' does not name a type
   11 |  value= 10;
      |  ^~~~~
MainClass.h:12:2: error: 'charecter' does not name a type
   12 |  charecter='a';
      |  ^~~~~~~~~
MainClass.h:16:2: error: 'protected_stuff' does not name a type
   16 |  protected_stuff = 2;
      |  ^~~~~~~~~~~~~~~
MainClass.h:21:2: error: 'public_stuff' does not name a type
   21 |  public_stuff = 3;
      |  ^~~~~~~~~~~~

后来我修改了MainClass.h,代码运行正常。

#ifndef MAINCLASS
#define MAINCLASS


class MainClass{

private:
    int value= 10;
    char charecter='a';

    // value= 10;
    // charecter='a';

protected:
    int protected_stuff= 2;
    // protected_stuff = 2;


public:
    int public_stuff = 3;
    // public_stuff = 3;

};

#endif

我的问题是我做错了什么?我尝试查看关于 SO 的各种其他问题,但找不到类似的内容:

【问题讨论】:

  • 你不能在函数之外有代码(例如像value= 10;这样的赋值)。与stackoverflow.com/questions/33335341/…stackoverflow.com/questions/16938810/… 相同
  • 我应该已正确阅读 C++ 中的“Y 未命名类型”错误...请将此问题作为副本关闭。
  • 你链接的那个“初始化类变量的正确位置?”本质上是相同的问题:您和那个 OP 都试图将 instance 变量视为属于该类。请注意,在某些其他语言(例如 Python)中,类似的代码创建属于该类的内容。

标签: c++ class


【解决方案1】:

您的错误与继承无关。如果没有任何继承,相同的代码将是一个错误。

在 C++ 中,像 value = 10; 这样的语句必须放在函数或构造函数中。所以这没关系(构造函数中的语句)

class MainClass{
    int value= 10;
    MainClass()
    {
        value = 10;
    }
};

这是(函数内的语句)

class MainClass{
    int value= 10;
    void function()
    {
        value = 10;
    }
};

另一方面,int value = 10; 是一个声明,因此它可以放在函数之外。

这是非常基本的 C++ 语法和语义。您需要了解声明和声明之间的区别。它建议我在处理继承之前需要花更多时间学习 C++ 的基础知识。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-24
    • 1970-01-01
    • 1970-01-01
    • 2011-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多