c++ - 构造函数被调用两次

标签 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
};

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

最佳答案

您没有 = 运算符接受 std::string(或 char*)的 RHS,因此,文字“3”被构造为 LINT,然后使用 = 运算符进行分配。

编辑:至于代码中的第二个问题,您需要在 std::string 上调用 c_str() 以获取 char* 字符串的缓冲区,然后将发生与您的文字 3 相同的事情。

关于c++ - 构造函数被调用两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2965495/

相关文章:

c++ - Boost Beast 握手 : sslv3 alert handshake failure error

c++ - printf 的 "precision"说明符的类型是什么?

c++ - memset 函数在我的 C++ 动态数组初始化中不起作用

c++ - 保存 ostringreader.str().c_str()

c++ - 在 C++ 中使用指针时的内存管理

c++ - 对符号 '_ZNSt8ios_base4InitD1Ev@@GLIBCXX_3.4' 的 undefined reference 在 Ubuntu 上构建 OpenCV

c++ - Visual Studio 2013 编译成功但有明显错误

c++ - 如何在 SDL 2 中获取并保存 BMP 屏幕截图?

c++ - 在 C++ 中使用 Rcpp header

c++ - 根据 C++ 中的数据类型设置默认值