你好,我是 C++ 新手,
我可以使用Example example("123")创建类的新实例
我有两个问题
我知道我们无法像
if(example ==NULL)
那样检查对象是否为 null,因为这不是一个指针,我们还有其他方法可以做到这一点吗?我有一个返回对象的方法,例如:如何返回 null?
Example get_Example() { if (example.getName().empty() { Example example("345"); return example; } return NULL // i cannot return null. }
我可以做这样的事情吗?
Example get_Example() {
Example example;
if (example.getName().empty() {
example = Example example("345");
return example;
}
return NULL // i cannot return null. How
}
example = Example example("345");
我知道这很愚蠢但是如果没有指针我该如何做到这一点。
最佳答案
使用指针,
示例 *ex = NULL
。构造默认的
null_example
并重载==
Example e; if (e == null_example) { e.init(); }
但您可以只提供一个
is_init()
函数。Example e; if (!e.is_init()) { e.init(); }
您的
get_example
可能类似于:void get_example(Example &e) { // method2 or method3 }
关于c++ - 在 C++ 中创建分配对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16375223/