【问题标题】:Unable to access class function using pointers无法使用指针访问类函数
【发布时间】:2016-10-04 09:39:38
【问题描述】:

在尝试访问我的类成员的功能时,使用指针时找不到它们。这是一个更大项目的一部分,并尽可能简化了问题。请注意,错误发生在 void getthenumberhere... 内部,无法检测到 getIDnumber 函数:

#include <iostream>
#include <stdlib.h>
#include <vector>
#include "windows.h"
#include <stdio.h>
//#include <math.h>
#include <string>
using namespace std;

class Person
{
public:
    Person(int);
    ~Person();
    vector<RECT>* processrectangles;

    int Person::getIDnumber();
private:
    int IDnumber;

};

Person::Person(int x)
{
    IDnumber = x;
}
Person::~Person()
{
}

int Person::getIDnumber() {
    return IDnumber;
}

void getthenumberhere(vector<Person>* thisone) {
    int outID = *thisone[1].getIDnumber(); //IT CANT FIND THIS FUNCTION
}


int main() {
    int NextID = 1;

    vector<Person> People;
    Person newguy(1);
    People.push_back(newguy);
    getthenumberhere(&People);
    return 0;
}

【问题讨论】:

  • 在编程中以0开始计数,所以应该使用(*thisone)[0].getIDnumber()
  • 只是一个评论:如果你在做 C++,包括 cstdlibcstdio 而不是 stdlib.hstdio.h (和 cmath 而不是 math.h 如果你取消注释行)

标签: c++ function class pointers


【解决方案1】:

使用括号避免歧义:

((*thisone)[1]).getIDnumber();

你也可以这样做

thisone->operator[](1).getIDnumber();

按照 cmets 的建议。

另外,在声明时写下这个:

int getIDnumber();

而不是int Person::getIDnumber();。声明成员函数时不应使用解析运算符。

【讨论】:

  • -&gt; 也是游戏的一部分。
  • @skypjack 你能建议在这种情况下如何使用-&gt;吗?
  • @user3286661 [] 也称为operator[],它是一种成员方法,您可以像其他任何方法一样调用。
  • @skypjack 请告诉我正确的语法,因为v-&gt;[index] 无法编译。
  • @user3286661 您仍然可以通过其名称调用操作员,例如this。不过,我看起来并不完全清楚。
猜你喜欢
  • 2015-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-03
  • 1970-01-01
相关资源
最近更新 更多