gpt4 book ai didi

c++ - 类c++头文件的重新定义

转载 作者:行者123 更新时间:2023-11-27 23:09:19 24 4
gpt4 key购买 nike

主类:

#include "otherClass.h"

using namespace std;

int main() {
a cl;
return 0;
}

头文件:

#ifndef OTHERCLASS_H_INCLUDED_
#define OTHERCLASS_H_INCLUDED_

class a {
int add(int a, int b);
int subtract(int a, int b);
};

#endif

头文件对应的.cpp类

#include "otherClass.h"

class a {
int add(int a, int b) {
return (a + b);
}

int subtract(int a, int b) {
return (a - b);
}
};

错误:

Text.cpp:13: error: ‘cl’ was not declared in this scopeotherClass.cpp:3: error: redefinition of ‘class a’ otherClass.h:3:error: previous definition of ‘class a’

我有两个问题:首先,在我向头文件中添加一个类之前,该文件运行良好(仅包含函数)。添加类(class)后,出现上述两个错误。有人可以告诉我如何安排我的头文件来修复这些错误吗? IE。我想知道如何为包含类的文件制作头文件。

其次,如何获取它以便在主函数的范围内声明该类?

最佳答案

这就是您在 .cpp 文件中定义类的成员函数的方式:

#include "otherClass.h"

int a::add(int a, int b) {
return (a + b);
}

int a::subtract(int a, int b) {
return (a - b);
}

请注意,您已将成员声明为private,因此您无法对它们做很多事情。

关于c++ - 类c++头文件的重新定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21270782/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com