2011-04-15 54 views
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; 
} 

请大家弄清楚原因? 在此先感谢

+0

这里的错误,代码已经缩进 – 2011-04-15 09:26:21

+0

什么是错误您收到?你有没有考虑过使用'std :: vector'? – Naveen 2011-04-15 09:26:36

+0

newpro.cpp:在构造函数'contact :: contact()'中: newpro.cpp:16:错误:'((contact *)this)'中的'operator ='的模糊重载 - > contact :: name = 0' newpro.cpp:在全局范围内: newpro.cpp:7:错误:新类型可能没有在返回类型中定义 newpro.cpp:7:注意:(可能在定义'联系人后缺少分号') newpro.cpp:32:错误:在'main'声明中有两个或多个数据类型 – 2011-04-15 09:28:56

回答

1

你忘了;

class contact { 
    ... 
}; // <- ; is neccessary 
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() { } 
+0

那么应该将这些数据类型分配给收缩器吗?\ – 2011-04-15 09:33:21

+1

@Frustrated Coder:编辑回答这个问题。 – ildjarn 2011-04-15 09:34:47

+0

phonenumber是一个变量不是函数 – 2011-04-15 09:52:05

相关问题