在c++中创建一个赋值对象

Creating an assigning an object in c++

本文关键字:一个 赋值 对象 c++ 创建      更新时间:2023-10-16

你好,我是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. 使用指针Example *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++对象看作OOP或Java。示例不是参考。它是物体本身。它的存在是因为它已经被贴花了。

如果您可以为定义为null的对象定义一个"状态",那么检查null(或使其为null(是有意义的。

bor示例您可以定义

explicit operator bool() const方法,并且当对象成员具有您定义的表示"非空示例"的值时返回true。

检查空Example actualexample,此时仅为if(!actualexample)

另一个选项是使用Null对象模式。Null对象模式基本上允许yo返回一个完全构造的对象,您将其标识为Null。

链接的维基百科文章中的例子给出了一个很好的例子:

class animal 
{
public:
  virtual void make_sound() = 0;
};
class dog : public animal 
{
  void make_sound() { cout << "woof!" << endl; }
};
class null_animal : public animal 
{
  void make_sound() { }
};

记住,创建一个特定的"Null对象"(即在某个地方定义一个全局Example kNullExample;(不是一个好的解决方案,因为如果你将其分配给另一个示例对象(即Example newObject = kNullExample;(,你将无法识别该对象不再为Null的事实。

另一种选择是将布尔值存储在对象中的某个位置,并编写一个"IsNull(("函数。只有当你不能让你的类变成虚拟的(例如映射二进制文件(,或者你真的负担不起虚拟表跳转的费用时,这才是真正的解决方案。

不能以这种方式分配NULL指针,因为返回对象不是指针。如果你不想使用指针,一个可能的选项可能是使用一个特定的NULL示例对象。我的意思是用这个类的自定义属性检查对象实例是否为NULL。可以使用构造函数中传递的空字符串:

exampleNull = Example example(""); 

并检查字符串属性以验证您的"null"对象

但请记住:NULL只能分配给指针类型

不要生成返回值的方法,只需重写运算符==,并在那里生成控件,因此如果执行if(example ==NULL),控件的重载方法将返回所需的布尔值。