除了在类和程序之前,函数是否需要在其他任何地方声明?
Do functions need to be declared anywhere else besides in the class and before the program?
我一直在试图说服自己,相同类型的对象可以访问彼此的私有数据成员。我写了一些代码,我认为可以帮助我更好地理解正在发生的事情,但现在我从XCODE7(只有1)得到一个错误,说我正在使用未声明的标识符"组合"。"
如果有人能帮助我了解我的代码哪里出错了,我很乐意学习。
如果正常运行,我的代码应该只打印false。
#include <iostream>
using std::cout;
using std::endl;
class Shared {
public:
bool combination(Shared& a, Shared& b);
private:
int useless{ 0 };
int limitless{ 1 };
};
bool Shared::combination(Shared& a,Shared& b){
return (a.useless > b.limitless);
}
int main() {
Shared sharedObj1;
Shared sharedObj2;
cout << combination(sharedObj1, sharedObj2) << endl;
return 0;
}
combination
是Shared
类的成员函数。因此,它只能在Shared
的一个实例上调用。当您调用combination
时,您没有指定要调用哪个对象:
cout << combination(sharedObj1, sharedObj2) << endl;
^^^
Instance?
编译器报错,因为它认为你想调用一个叫做combination
的函数,但是没有。
所以,你必须指定一个实例:
cout << sharedObj1.combination(sharedObj1, sharedObj2) << endl;
在这种情况下,无论在哪个实例上调用它都无关紧要,所以你应该将combination
设置为静态,这样你就可以执行
cout << Shared::combination(sharedObj1, sharedObj2) << endl;
相关文章:
- .cpp和.h文件中的模板专用化声明
- 嵌入方指针压缩已禁用
- 未在作用域中声明unordered_map
- C++避免重复声明的语法是什么
- 如何确保C++函数在定义之前声明(如override关键字)
- 错误:未在此范围内声明'reverse'
- 奇怪的(对我来说)返回声明 - 在谷歌上找不到任何关于它的信息
- 为什么在定义函数之前先声明它
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- #ifdef和未声明的标识符
- 没有显式声明的int[]中的foreach
- 在基于范围的for循环中使用结构化绑定声明
- 在将变量声明为引用时,堆在释放后使用
- C++:无法访问声明的受保护成员
- 为什么我不能在一个类的不同行中声明和定义成员变量?
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 使用cmake从源代码构建MySQL连接器/C++失败(与以前的声明冲突)
- 在函数内部的声明中初始化数组,并在外部使用它
- Visual Studio中的函数声明和函数定义问题
- c++类声明时,相同的例程,不同的成员变量类型