2

基本上,在其重载赋值运算符中调用类的构造函数是否可接受的编程实践/风格?如果不是,为什么不呢?

例子:

所以我有一个有 3 个数据成员的类,一个名为“value”的动态 int 数组,它保存一个大数字的数字,一个int length表示数字中的位数,&一个int maxLength表示数字的最大长度(大小动态数组)

这是我的带有参数 int 的构造函数:

bigInt::bigInt(const int &rhs){
    //turn num_ into a string 'num'
    stringstream ss;
    ss << num_;
    string num = ss.str();
    length = strlen(num.c_str());
    maxLength = (length - (length%16)) + 16;
    value = new int[maxLength];
    for(int i=1; i<=length; i++){
        value[i-1] = num.at(length-i) - '0';
    }
}

这是我的重载赋值运算符,其中右侧是常规 int 此方法调用构造函数:

bigInt bigInt::operator=(const int &rhs){
    *this = bigInt(rhs);
    return *this;
}

编辑:我想我应该用不同的措辞。我不是指 COPY 构造函数,而是具有非类实例参数的常规构造函数,以及 rhs 与 lys 类型不同的重载赋值运算符

4

3 回答 3

1

This is not an unreasonable way to implement your assignment operator, since it allows you to utilize existing code, and provides the strong guarantee as long as your copy assignment operator does.

Two points of note however: First, make sure that your copy constructor, copy assignment operator, and destructor are all implemented properly or you'll start having memory management problems. Second, the C++ language ALREADY provides a class with elements, a length, and a max length: It's called std::vector and if you change your code to use it, you don't need to write the copy constructor, copy assignment operator, and destructor at all, as they'll just behave properly!

Also, your assignment operator should return by reference (or if you really don't want chaining, void). Returning by value will someday cause a bug when a chained assignment doesn't work as expected.

于 2013-04-04T14:30:50.580 回答
1

在赋值运算符的实现中调用复制构造函数并没有错(当然,除非复制构造函数本身是根据赋值来实现的)。实际上,这是一个常见的习惯用法:制作本地副本,然后将数据与当前实例交换。(当然,这假设您有一个专门的交换。仅 std::swap在赋值运算符中调用对象本身 并不是一个好主意。创建一个新实例,然后经常交换对象的各个组件。或者创建一个交换组件并调用它的自定义交换函数。)

于 2013-04-04T13:43:29.660 回答
0

反之更好。完全没问题。

但是,不要忘记在复制构造器中你必须重做你在构造器中所做的事情;即,初始化您在类中的任何变量,这在重载的赋值运算符函数中不是必需的。

于 2013-04-04T13:24:09.567 回答