【问题标题】:Request for Member in ' ' whitch is a non-class type对非类类型“ ”中的成员的请求
【发布时间】:2014-12-22 16:03:12
【问题描述】:

我想创建一个 Accounts 对象数组,以便管理它们从文件中加载所有内容(通过结构)。 我很新学习 c++,但我不知道我做错了什么。

做什么:Account** accounts[50] ? ""accounts[i] = new Account*; ""accounts[i]->newAccount(i, id_string, pw_string, level_int); 错误消息:request for member 'newAccount' in '* accounts[i]', which is of non-class type 'Account*'

AccountManagerFrm.cpp // 运行一切的主文件

#include "AccountManagerFrm.h"
#include "Account.h"
#include "ladeAccounts.h"
using namespace std;
Account** accounts [50];
void AccountManagerFrm::createAccountClick(wxCommandEvent& event)
{    

    accounts[i] = new Account*;
    accounts[i]->newAccount(i, id_string, pw_string, level_int);  // ERROR LINE    

}

帐户.cpp

class Account
{
    struct iAccount
    {
        string ID;
        string password;
        int level;
    };
Account()
    {

    } 
void newAccount(int anzahl, string username, string pw, int lvl)
    {
        iAccount neu;
        neu.ID = username;
        neu.password = pw;
        neu.level = lvl;

    }


};

帐户.h

#include <string>
using namespace std;
class Account{

public: 
    Account();    
    void newAccount(int anzahl, string username, string pw, int lvl);   
    void getInformationFromFile();


};

【问题讨论】:

  • Accounts[i] 是指向 Account* 的指针,而不是 Account*

标签: c++ object types


【解决方案1】:

我想创建一个 Accounts 对象数组

只是

Account accounts[50];

不是你奇怪的指针数组。然后您可以使用. 访问其中一个

accounts[i].newAccount(i, id_string, pw_string, level_int);

您还需要修正类定义。标题中的定义本身需要包含所有成员。此外,标题应该有一个保护,以避免在多次包含标题时出现错误。将namespace std; 转储到全局命名空间是个坏主意;这会污染包含标头的每个人的全局命名空间。整个标题应该是这样的

#ifndef ACCOUNT_H
#define ACCOUNT_H

#include <string>

class Account {
public: 
    Account();    
    void newAccount(int anzahl, std::string username, string std::pw, int lvl);   
    void getInformationFromFile();
private:
    std::string ID;
    std::string password;
    int level;
};
#endif

源文件应该只定义成员函数,而不是重新定义整个类:

#include "Account.h"

Account::Account() {}

void Account::newAccount(int anzahl, std::string username, std::string pw, int lvl)
{
    ID = username;
    password = pw;
    level = lvl;
}

如果您正在为基本的类定义而苦苦挣扎,那么您真的应该阅读good introductory book。这是一门复杂的语言,你永远无法通过猜测语法来学习它。

【讨论】:

  • 我已经尝试过了,但是我得到了错误:[Linker Error] undefined reference to `Account::newAccount(int, std::string, std::string, int)' 如果我尝试使用构造函数“Account(int, ... ... ...) 我得到 ERROR: invalid use of 'Account::Account'
  • @spyce 这是因为您定义了两个Account 类,一个在标题中,一个在cpp 中。 “header-Account”中的成员函数没有定义。你应该在你的好书中复习如何定义类及其成员的基础知识。
  • @Mike Seymour 你能给我一个头文件+主类中使用的.cpp文件的例子吗?我现在没有一本书更改了很多,但仍然出现错误:'Account::Account'的使用无效
  • @spyce:我添加了应该可以工作的示例(尽管我没有测试过它们)。但是如果你想学习 C++,你真的需要一本书。
猜你喜欢
  • 2019-04-28
  • 1970-01-01
  • 2022-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-20
相关资源
最近更新 更多