C ++ const char *赋值运算符重载

时间:2019-08-02 18:19:25

标签: c++

如何处理class ScheduledTaskServiceSpec extends Specification implements ServiceUnitTest<ScheduledTaskService>{ @Shared @AutoCleanup HibernateDatastore hibernateDatastore @Shared AutoTimestampEventListener timestamper void setupSpec() { hibernateDatastore = new HibernateDatastore(RegistrationCode) timestamper = hibernateDatastore.getAutoTimestampEventListener() } @Transactional @Rollback void 'some test method'() { when: timestamper.withoutDateCreated(MyDomainClass) { MyDomainClass mdc = new MyDomainClass(name:"foo") mdc.dateCreated = new Date() - 20 } then: MyDomainClass.findByName("foo").dateCreated < new Date() } }

const char *

更新

Obj(const Obj& o); // <--
Obj& operator=(const Obj& o);// <-- How to do it right?

// Obj(const Obj& o); // <--
// Obj& operator=(const Obj& o);

class Obj
{
protected:
  const char * name;
  const char * desc;
public:
  Obj(const char * _name,
      const char * _desc)
  :name(_name)
  ,desc(_desc)
  {
    //
  }

  Obj(const Obj& o); // <--
  Obj& operator=(const Obj& o);// <-- Have no idea how to implement this...

  virtual ~Obj(){}
};

class B:public Obj
{
    float v1, v2;
    B(float a, float b)
    :v1(a)
    ,v2(h)
    ,Obj("B","class")
    {
      //
    }

};

1 个答案:

答案 0 :(得分:2)

编辑:您的代码有一个严重的错误,形式为try { throw Error('Example error') } catch (e) { console.log(e) } ,它会向成员的外部指针赋值,而不是复制其数据。忘记所有的 ,包括我的答案,然后使用Obj("B","class")

使用指针复制对象意味着您要序列化指针数据。如果是字符串,则strcpy / memcpy就足够了:

std::string

但是,请始终使用Obj& operator=(const Obj& o) { name = new char[o.namesize + 1]; // must keep the size unless it's a string, so you can assume the size with strlen(). strcpy_s(name,o.namesize + 1,o.name); namesize = o.namesize; // With strlen name = new char[strlen(o.name) + 1]; strcpy_s(name,strlen(o.name) + 1,o.name); return *this; } 并忽略所有这些东西,因为它将由STL自动处理,包括移动语义,自动内存管理等。