创建类成员函数

时间:2017-06-26 13:20:54

标签: c++ arrays function class oop

我试图为我创建的类创建一个类成员函数。目前,Class有一个2D数组,通过从文件中读取文本来填充。

我接下来尝试做的是通过成员函数操作数组来执行不同的任务(我创建一个菜单驱动的程序)。

function Get-ChildItemRecursive {
  [CmdletBinding()]
  Param(
    [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
    [string]$FullName,
    [Parameter(Mandatory=$false)]
    [int]$Depth = 0
  )

  Process {
    if ($Depth -ne 1) {
      $newDepth = if ($Depth -gt 1) { $Depth - 1 } else { $Depth }
      Get-ChildItem -Path $FullName -Directory | Get-ChildItemRecursive -Depth $newDepth
    }
    Get-ChildItem -Path $FullName
  }
}

Get-ChildItemRecursive -FullName 'H:\demo' -Depth 5 |
    Where {$_.PSIsContainer -eq $True} |
    ...

从我的主要产品中我有一个用于调用功能的开关盒。

class Person
{
private: 
    string sname;
    string fname;
    string sex;
    string dob;
    string array[4][8];
public:
    Person();
    void getSex(); <-- This is where I'm struggling
};

然后我拥有了我在下面创建的功能:

int main()
{
    switch (case)
    {
    case '1':
        Person();
        break;
    case '2':
        Person::getSex();
        break;
}

然而,在我创建的功能中,我在阵列上收到错误消息:

&#34;非静态成员引用必须与特定对象相关。&#34;

任何人都可以看到我出错的地方,请帮助我纠正它吗?

修改

所以我现在知道我不应该使用静态而是(至少)应该使用void(虽然有一个实际的返回类型会更好 - 但如果我将函数设置为void我的数组变得不确定?

1 个答案:

答案 0 :(得分:1)

  

&#34;非静态成员引用必须与特定对象相关。&#34;

您的数组不是static,而getSex()static。但是,将该方法标记为static是否有意义?我的意思是每个Person都有性别(男性为女性)。

PS:通常getter函数返回一些东西,而你的函数有返回类型void。我怀疑你这样做只是为了测试(因为你打印的东西)。

相关问题