预期表达式对象数组
Expected an expression Array of Object
如何解决此错误?
类名需要 2 个参数 { 字符串, int}.
className *Object;
Object= new className[2];
Object[1]= { name, id}; // ERROR
.
首先,您需要了解代码在做什么:
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;
}
如果您使用矢量,那么您不必担心释放您用 new 分配的内存。
相关文章:
- 销毁C++中动态分配的内存(数组对象)
- 数组对象的生存期是否在重用其元素存储时结束?
- 为什么顶点数组对象会导致错误?
- 具有纯虚函数和指针数组对象类型的父类的指针数组
- 这是使用构造函数初始化数组对象的最佳方法吗?
- OpenGL 顶点数组对象与 tinyobjloader
- 将数组/对象/结构列表从C#库中传递给C MFC应用程序
- C++ RapidJson 帮助反序列化数组对象
- ptrdiff_t可以表示指向同一数组对象元素的指针的所有减法吗?
- 检查成员函数是否返回临时对象或数组对象
- 为什么 std::variant 不能容纳数组对象类型,而联合可以?
- 当数组对象以函数参数传递时,为什么复制构造函数会自称
- 如何使用箭头指针打印出一类数组对象,这些对象中有多个分数
- C++17 std::shared_ptr<> 类数组对象的重载运算符 []
- 添加两个具有运算符重载的数组对象,从而导致分段错误
- opengl:两个不同的矢量可以绑定到同一个顶点数组对象吗
- 使用相同的数据填充数组对象或使用指针
- 方法用于最快的分配,并且不需要将动态大小的数组对象作为局部变量
- 如何将2d数组对象传递给c++中的函数
- ReferenceTable溢出(jni-android),数组对象释放