【问题标题】:Can i call a class in my function within said class?我可以在所述类中调用我的函数中的类吗?
【发布时间】:2020-05-12 20:06:50
【问题描述】:

由于我对 c++ 和课程有点生疏,我不确定我是否只是犯了一些重大错误,或者是否不可能,也许这里的任何人都可以让我变得更聪明。

我正在尝试为我的“位置”类创建一个比较函数。这样我以后可以调用 pos1.compare(pos2) 并得到一个布尔值。 出于某种原因,它没有编译,我认为这可能是因为我尝试在其内部调用该类?

我使用 c++,windows,我用 minGW 编译。

class myPossition{
  public:
    int x;
    int y;
  private:
    myPossition( int nx, int ny ){
        x = nx;
        y = ny;
    }
    bool compare( myPossition compPos ){
        if(compPos.x==x&&compPos.y==y)return true;
        return false;
    }

};

【问题讨论】:

  • mingw 给我的错误是“候选人需要 2 个参数,提供了 0”“候选人:'constexpr myPossition::myPossition(const myPossition&)'”

标签: c++ function class


【解决方案1】:

我假设“不工作”是指您编写的代码如下:

int main() {
    myPosition a(1, 2);
    myPosition b(3, 4);
    std::cout << a.compare(b) << std::endl;
}

它没有编译。 答案是您应该将myPosition( int nx, int ny )bool compare( myPosition compPos ) 都放入public 部分,而不是private

您可以在此处阅读有关访问说明符的更多信息https://en.cppreference.com/w/cpp/language/access

【讨论】:

  • 我的意思是'不编译',对不起。我会通读你给我的页面,看看我是否可以通过将它们都公开来修复它。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-06
  • 2011-06-10
  • 2012-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多