【问题标题】:Expected an expression Array of Object需要一个对象的表达式数组
【发布时间】:2014-12-09 13:37:24
【问题描述】:

我该如何解决这个错误?

className 有 2 个参数 { string, int} .

className *Object; 

Object= new className[2]; 



Object[1]= { name, id};  // ERROR 

.

【问题讨论】:

  • 什么编程语言?
  • 然后将其作为标签添加到您的问题中。
  • 如果您的意思是className 有一个带有两个参数的构造函数,那么这将无济于事。当您使用new[] 创建数组时,数组的每个元素都由默认构造函数(必须可用)初始化。请改用std::vector<className> 及其emplace_back 方法。

标签: c++ arrays class pointers visual-c++


【解决方案1】:

首先你需要了解你的代码在做什么:

int main()
{
    className *object;              // Create a pointer to className type.
    object = new className[2];      // Create an array of two className objects.
                                    // note here you are instantiating className.
                                    // This is possible because it have a default constructor.

    object[1] = { "John Doe", 1 };  // Here you're assigning new values to a existing object trough 
                                    // the assignment operator(=). As you're working with visual-c++
                                    // the compiler by default will generate the operator=() function, but 
                                    // if all conditions are not there the compiler can't generate it.
                                    // You need to add to className another constructor.

    cout << object[1].get_name() << endl;
}

以下类将起作用:

class className
{
public:
    className(string pname, int pid) :name(pname), id(pid){}  // New constructor.
    className(){}
    string get_name(){ return name; }
    int get_id(){ return id; }
private:
    int id;
    string name;
};

另一方面...

你正在使用 c++,好吧,使用它

你的主要功能可以写成如下:

int main()
{
    vector<className> objects;              // A vector of className objects.
    objects.push_back({ "John Doe", 1 });   // Add an object to vector.
    objects.push_back({ "John Mark", 2 });  // Add another object to vector.

    cout <<  objects[0].get_name() << endl;  // Access to an object in vector.

    return 0;
}

如果您使用vector,那么您不必担心释放您使用new 分配的内存。

【讨论】:

    猜你喜欢
    • 2019-07-12
    • 1970-01-01
    • 1970-01-01
    • 2019-10-01
    • 2015-11-12
    • 1970-01-01
    • 2017-08-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多