【问题标题】:assignment operator doesnt work赋值运算符不起作用
【发布时间】:2014-04-06 15:16:28
【问题描述】:

我有一个构造函数来表示大数字并将它们存储到向量中: 我的类由一个向量、一个布尔值和一个整数组成,应该代表大数字。

    CBigInt(const char* str2)
{
    string str=string(str2);
    num.resize(200000);
    if (str[0]=='-') 
    {
        signe=true; 
        pos=str.length()-1;
        for (int i=pos;i>0;i--)
        {
            num[pos-i]=str[i]-48;
        }
    }
    else
    {
        signe=false; 
        pos=str.length();
        for (int i=pos;i>=0;i--)
        {
            num[pos-i-1]=str[i]-48;
        }
    }       
}

我得到一个错误:http://pastebin.com/cy82XaLF

【问题讨论】:

  • 字符串是std::string?
  • 是的,字符串是 std::string。
  • 好吧,你可以做CbigInt foo = std::string("11113"),但我仍然想知道为什么它不能隐式地从const char[]构造字符串
  • 顺便说一句,如果你有 c++11 支持,你可能想定义一个 user-defined literal
  • 提示:避免使用幻数,而是使用字符文字。这远没有那么令人困惑。 '0'.

标签: c++ constructor overloading operator-keyword


【解决方案1】:

在已有的构造函数之上声明并实现一个额外的构造函数:

CBigInt::CBigInt(const char* str):CBigInt(string(str)){}

【讨论】:

  • 但这不会混淆两个构造函数吗?
  • @stepanBY: 1. 你应该更新你的问题而不是改变它,因为现在之前给出的答案似乎都不相关。 2.针对当前问题,需要提供实际导致运行时错误的代码(而不仅仅是CBigInt类)。
【解决方案2】:

一个转换序列最多只能包含一个隐式用户定义转换。你的包含两个:const char[]string,然后是 stringCBigInt

一个简单的解决方法是显式地进行一次转换:

CBigInt autre("123456789012345678901111");

【讨论】:

  • 或者直接使用 const char * 会更好?
【解决方案3】:

可能它们不起作用,因为编译没有在同一操作中提供两个隐式转换,一个从Const Char*String,和StringCBigInt。只有当类型为CBigInt 时才可能调用operator =

这可以在与您的类正确编译的代码和平中得到修复:

   CBigInt a("99") //justo one implicit convertion, to const char * to string
   string std;
   a = std; //just one implicit convertion, to String to CBigInt
   a = string("99"); //just one implicit convertion, to String to CBigInt

我的建议是将您的代码从 CBigInt(string) 复制到 CBigInt(const char*) 和 adpatad 以在字符串末尾查找 '\0'。

我必须给您的另一个建议是将您的签名从CBigInt(string) 交换为CBigInt(const string&),它更快,因为不复制字符串并且无需更改代码。

【讨论】:

  • 但是在那之后,我是否必须调整我重载的所有运算符?通过用 const *char 替换 const 字符串?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-04
  • 2011-08-02
  • 2019-10-06
  • 2011-11-16
  • 2013-11-30
  • 2015-10-02
  • 2020-08-10
相关资源
最近更新 更多