用c ++创建一个类对象数组

Fru*_*der 1 c++

嗨,大家好我想创建一个类对象数组....这样我就可以在运行时继续创建尽可能多的对象,并在需要时编写以下代码,但它给了我错误:

class contact{
public:
    string name;//ALL CLASS VARIABLES ARE PUBLIC
    int phonenumber;
    string address;

    contact(){//Constructor
        name= NULL;
        phonenumber= NULL;
        address= NULL;
    }

    void input_contact_name(string s){//function to take contact name
        name=s;
    }
    void input_contact_number(int x){//function to take contact number
        phonenumber=x;
    }
    void input_contact_address(string add){//function to take contact address
        address=add;
    }
}

int main(){
    contact *d;
    d= new contact[200];
    string name,add;
    int choice;//Variable for switch statement
    int phno;
    static int i=0;//i is declared as a static int variable
    bool flag=false;
    cout<<"\tWelcome to the phone Directory\n";//Welcome Message
    cout<<"Select :\n1.Add New Contact\n2.Update Existing Contact\n3.Delete an Existing Entry\n4.Display All Contacts\n5.Search for a contact\n6.Exit PhoneBook\n\n\n";//Display all options
    cin>>choice;//Input Choice from user
    while(!flag){//While Loop Starts
        switch(choice){//Switch Loop Starts
        case 1:
            cout<<"\nEnter The Name\n";
            cin>>name;
            d[i]->name=name;
            cout<<"\nEnter the Phone Number\n";
            cin>>phno;
            d[i]->input_contact_number(phno);
            cout<<"\nEnter the address\n";
            cin>>add;
            d[i]->input_contact_address(add);
            i++;
            flag=true;
        }
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

有人可以找出原因吗?提前致谢

ild*_*arn 6

很多问题:

  1. 正如maverik所说,在班级的右大括号上缺少分号
  2. 使用stringusing namespace std;using std::string;(或#include <string>就此而言)
  3. 同上#2 cincout(和<iostream>)
  4. d[i]->是错的; d[i]contact&,而不是contact*,所以使用.而不是->
  5. name= NULL;并且address= NULL;是无意义的 - string不是指针类型,并且已经默认构造为空
  6. phonenumber= NULL;技术上是有效的,但仍然'错'

还有,好主,在你的代码中使用一些空格.

编辑(回应评论):您的构造函数应如下所示:

contact() : phonenumber() { }
Run Code Online (Sandbox Code Playgroud)