【发布时间】: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 的各种其他问题,但找不到类似的内容:
- error: 'x' does not name a type
- error: ‘X’ does not name a type X in template functions
- "X does not name a type" error in C++
- "Y does not name a type" error in C++
- Error C++ : does not name a type
- Another "x" does not name a type error
- Correct place to initialize class variables?
- Initialisation and assignment
【问题讨论】:
-
你不能在函数之外有代码(例如像
value= 10;这样的赋值)。与stackoverflow.com/questions/33335341/… 和stackoverflow.com/questions/16938810/… 相同 -
我应该已正确阅读 C++ 中的“Y 未命名类型”错误...请将此问题作为副本关闭。
-
你链接的那个“初始化类变量的正确位置?”本质上是相同的问题:您和那个 OP 都试图将 instance 变量视为属于该类。请注意,在某些其他语言(例如 Python)中,类似的代码会创建属于该类的内容。