在代码中:
//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/