gpt4 book ai didi

c++ - 除了在类中和程序之前,是否还需要在其他任何地方声明函数?

转载 作者:行者123 更新时间:2023-11-30 05:22:07 27 4
gpt4 key购买 nike

我一直试图说服自己相同类型的对象可以访问彼此的私有(private)数据成员。我写了一些我认为可以帮助我更好地理解正在发生的事情的代码,但现在我从 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;

关于c++ - 除了在类中和程序之前,是否还需要在其他任何地方声明函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39820772/

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