尝试在没有new的情况下使用我的自定义类构造函数
trying to use my custom class constructor without new
来自java,我希望在创建新的自定义或其他库的对象时不必处理取消分配。
今天我试图创建一个实体对象的实例,比如:
entity cube = new entity("entityName")
因为这就是实体构造函数的格式但我得到以下错误:
cannot convert from |entity *| to |entity|
我注意到,如果我只是删除new
关键字,就不会有错误,我想知道两件事。
使用
new
时的错误是什么意思?(我对指针的工作方式很有信心,但并不完全像刚开始使用java时那样。)我可以在没有
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
}
还有更多的选项,比如按值传递实例(在这种情况下不推荐),或者在动态内存中创建实例并取消
- 使用new时的错误意味着什么?(我对指针的工作方式很有信心,但不像刚开始使用java那样完全有信心。)
没有。C++与此不同,您不使用分配(new)来初始化cube
:
entity cube("entityName");
- 我可以在没有新关键字的情况下创建这样的对象吗?或者甚至可以创建一个对象吗?(因为没有错误。)
没有。请参见上文。("因为没有错误。"我对此表示怀疑,如果从指针分配entity
,至少应该有编译器警告。)
相关文章:
- 我的自定义使用 std::unordered_map 的性能非常慢
- Metatrader 5 向导无法识别我的自定义交易信号模块
- (C++)我的自定义数组无法初始化(编译错误)
- 提升::any_cast到我的自定义类
- Qt - 为什么我无法在主窗口中为我的自定义按钮触发 mousePressEvent
- 为什么我的自定义"::swap"函数没有被调用?
- std::sort 在我的自定义迭代器上不起作用
- 我的自定义 C++ DLL 的 C# 项目中的 DLL 端口有什么问题?
- 为什么 Tensorflow 找不到我的自定义操作的 GPU 内核?
- 为什么我的自定义界面总是返回不可能的0x80040213/VFW_E_NO_CLOCK
- 为什么我的自定义分配器比默认分配器慢
- 没有用于初始化我的自定义分配器的匹配构造函数
- 如何为我的自定义向量类实现类似 vector.insert 的方法
- 如何实现我的自定义范围循环
- 为什么选择我的自定义OP的CPU实现
- 如何从我的自定义类中的现有类调用方法 (arduino)
- 我的自定义迭代器有什么问题
- 我的自定义比较不起作用
- 尝试在没有new的情况下使用我的自定义类构造函数
- 如何将我的自定义模块与 Omnet++INET 的简单模块相结合