c++ - 在 C++ 中创建分配对象

标签 c++

你好,我是 C++ 新手,

我可以使用Example example("123")创建类的新实例

我有两个问题

  1. 我知道我们无法像 if(example ==NULL) 那样检查对象是否为 null,因为这不是一个指针,我们还有其他方法可以做到这一点吗?

  2. 我有一个返回对象的方法,例如:如何返回 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"); 我知道这很愚蠢但是如果没有指针我该如何做到这一点。

最佳答案

  1. 使用指针,示例 *ex = NULL

  2. 构造默认的 null_example 并重载 ==

    Example e;
    if (e == null_example) {
        e.init();
    }
    
  3. 但您可以只提供一个 is_init() 函数。

    Example e;
    if (!e.is_init()) {
         e.init();
    }
    
  4. 您的get_example可能类似于:

    void get_example(Example &e) {
         // method2 or method3
    }
    

关于c++ - 在 C++ 中创建分配对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16375223/

相关文章:

c++ - QT5.3 如何将我的 Qobject 添加到 QQmlEngine 并通过 QML 访问它的属性?

c++ - 在列表中使用 QWidget 指针时,它们无法显示

c++ - 保证有效的字符串作为函数参数

C++ friend 继承?

c++ - 根据编译时常量,使用 #define'd 或 typedef'ed 相同的标识符是否被认为是可接受的做法?

c++ - 在 Release 中获取 std::bad_alloc 但在 Debug 中不获取

c++ - 量化库 + Python : TARGET() macro and default calendar (RuntimeError: option expired)

c++ - 如何校准直观的指向机构

c++ - 在 C++ 中为指针数组定义 NULL

c++ - 延期成员(member) build