尝试在没有new的情况下使用我的自定义类构造函数

trying to use my custom class constructor without new

本文关键字:我的 自定义 构造函数 情况下 new      更新时间:2023-10-16

来自java,我希望在创建新的自定义或其他库的对象时不必处理取消分配。

今天我试图创建一个实体对象的实例,比如:

entity cube = new entity("entityName")

因为这就是实体构造函数的格式但我得到以下错误:

cannot convert from |entity *| to |entity|

我注意到,如果我只是删除new关键字,就不会有错误,我想知道两件事。

  1. 使用new时的错误是什么意思?(我对指针的工作方式很有信心,但并不完全像刚开始使用java时那样。)

  2. 我可以在没有new关键字的情况下创建这样的对象吗?或者甚至可以创建对象吗?(因为没有错误。)

new entity("entityName")

意思是"在空闲存储中创建entity的实例并返回指向该实例的指针"
由于指向entity的指针与entity的指针不同,因此除非有其他构造函数,否则无法使用该值初始化entity

做你想做的事的方法是

entity cube("entityname");

你需要一本关于C++的好书。

首先,我建议您阅读C++教程。它比Java复杂得多。

这是一个非常部分的Java到C++的"如何转换"指南,我可以给你:

Java代码:

void sayHello(String name) {
    system.out.println("Hello, " + name);
}
public static void main(String args[]) {
    String name = "James";  //  <-- This string is of course created in the dynamic memory
    sayHello(name);   //  <-- "name" will be passed by reference to the "sayHello()" method
}

等价于C++-选项1

void sayHello(const std::string &name) {
    std::cout << "Hello, " << name << std::endl;
}
int main() {
    std::string name("James");  // <-- Variable is created on the stack
    sayHello(name);  // <-- Although "name" is not a pointer, it will be passed by reference to "sayHello", as "name" is defiend there with "&", which means that it is a reference
}

引用是一种非常"奇怪"的类型——它的行为就像一个局部变量,尽管它实际上指向的实例不必在当前函数的堆栈上,也不必在堆栈上。

C++-选项2

void sayHello(const std::string *name) {
    std::cout << "Hello, " << *name << std::endl;  // <-- dereferenceing "name" using a preceding star, as "cout" needs the variable itself and not its address
}
int main() {
    std::string *name = new std::string("James");  // <-- Instance is created in the dynamic memory
    sayHello(name);  // <-- Sending the pointer "name" to the "sayHello" function
    // You will need to free "name" somewhere in the code unless you don't care about memory leaks
}

还有更多的选项,比如按值传递实例(在这种情况下不推荐),或者在动态内存中创建实例并取消

  1. 使用new时的错误意味着什么?(我对指针的工作方式很有信心,但不像刚开始使用java那样完全有信心。)

没有。C++与此不同,您不使用分配(new)来初始化cube:

entity cube("entityName");
  1. 我可以在没有新关键字的情况下创建这样的对象吗?或者甚至可以创建一个对象吗?(因为没有错误。)

没有。请参见上文。("因为没有错误。"我对此表示怀疑,如果从指针分配entity,至少应该有编译器警告。)