【问题标题】:Error: Request for member ' ' in ' ' , which is of non-class type ' '错误:对“ ”中的成员“ ”的请求,它是非类类型“ ”
【发布时间】:2018-02-28 18:48:41
【问题描述】:

我无法识别此代码的问题...

这是类声明:

class PersonType{
public:
    PersonType();
    PersonType(string n, int id, string bd);
private:
    string name;
    int ID;
    string birthday;};

这就是问题所在:

PersonType family[20], newBaby("Anny Dube", 20180912, "2 Sept");

//family initialized here

for (int i = 0; i < 20; i++)
    if (family.birthday[5] == newBaby.birthday)
        cout << family.name[5] << " share a birthday with " << newBaby.name;

我在运行代码时遇到了他的错误:

错误:请求'family'中的成员'birthday',它是非类类型'PersonType [20]'|

错误:请求“family”中的成员“name”,它是非类类型“PersonType [20]”|

我知道姓名、ID 和生日是私密的这一事实是一个问题,但我知道如何解决这个问题。即使我将变量公开或使用访问器方法,我仍然会遇到这两个错误...

我已经阅读了一大堆与此问题相关的问题,但我能找到的都是关于指针、拼写错误的变量等。

似乎对此没有任何帮助......

请帮忙?

【问题讨论】:

    标签: c++ function class


    【解决方案1】:

    family.birthday[5] 应该是 family[5].birthday。您将获得 family 数组 (family[5]) 的第 5 个索引,然后访问其 birthday 字段。

    family.name[5] 也是如此 => family[5].name。

    但是请注意,name 和 birthday 都是私有成员,所以现在这段代码仍然会抛出错误。您需要将它们设为公共成员或创建访问器/修改器并调用它们。 (感谢@Borgleader!)

    【讨论】:

    • 耶!!这对我遇到的成员错误请求进行了排序,但现在我得到了这个错误: undefined reference to `PersonType::PersonType()' @scohe001
    • @BuzzLightYear 我看到你已经声明了你的默认构造函数,但是你确定实现它了吗?
    • 我忘记实现默认构造函数了!!!!谢谢@scohe001 现在所有问题都已排序
    • 您的意思可能实际上是family[i].name。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-27
    相关资源
    最近更新 更多