构造函数被调用两次

The*_* do 0 c++

在代码中:

//file main.cpp
LINT a = "12";
LINT b = 3;
a = "3";//WHY THIS LINE INVOKES CTOR?


std::string t = "1";
//LINT a = t;//Err NO SUITABLE CONV FROM STRING TO LINT. Shouldn't ctor do it?

//file LINT.h
#pragma once
#include "LINT_rep.h"
class LINT
{
private:
    typedef LINT_rep value_type;
    const value_type* my_data_;
    template<class T>
    void init_(const T&);
public:
    LINT(const char* = 0);
    LINT(const std::string&);
    LINT(const LINT&);
    LINT(const long_long&);
    LINT& operator=(const LINT&);
    virtual ~LINT(void);

    LINT operator+()const;               //DONE
    LINT operator+(const LINT&)const;//DONE
    LINT operator-()const;               //DONE
    LINT operator-(const LINT&)const;//DONE
    LINT operator*(const LINT&)const;//DONE
    LINT operator/(const LINT&)const;///WAITS FOR APPROVAL

    LINT& operator+=(const LINT&);//DONE
    LINT& operator-=(const LINT&);//DONE
    LINT& operator*=(const LINT&);//DONE
    LINT operator/=(const LINT&);///WAITS FOR APPROVAL
};
Run Code Online (Sandbox Code Playgroud)

在行号3而不是赋值optor ctor被调用.为什么?我愿意在某些服务器上卸载整个解决方案,否则很难将所有内容都放在这里.我也可以上传视频文件.另一件事是,当我实现这个赋值optor时,我得到一个错误,这个optor已经在obj文件中?这是怎么回事?

Don*_*nie 7

您没有=采用std::string(或char*)RHS 的运算符,因此,文字"3"正在构造为a LINT,然后使用您的=运算符进行分配.

编辑:至于在你的代码的第二个问题,你需要调用c_str()std::string得到char*的字符串缓冲区,然后同样的事情会发生,与您的文字3.


小智 6

赋值运算符将LINT对象作为参数,但是当你说:

a = "3";
Run Code Online (Sandbox Code Playgroud)

您正在将赋值操作传递给字符串文字,而不是LINT对象.编译器需要创建赋值操作可以使用的LINT对象,因此它调用构造函数const char *作为参数来执行该操作.