【问题标题】:A question about overloading a boolean operator in C++关于C++中布尔运算符重载的问题
【发布时间】:2020-02-25 13:14:34
【问题描述】:

对于这个赋值,我们不能使用 std::string。

我有一个构造函数,它接收以 DNA 链为模型的 C 字符串。

DNAStrand::DNAStrand(const char* startingString) {
    length = strlen(startingString);
    bases = new char[length + 1] {'A','C','G','T',0};
}

然后我尝试重载一个布尔运算符,该运算符将检查我创建的链与另一个链。

bool DNAStrand::operator==(const DNAStrand& other) const {
    if (length != other.length)
        return false; //can't be the same if we don't have same # items

    //Same size, walk through items looking for mismatch
    for (int i = 0; i < length; i++) {
        if (bases[i] != other.bases[i])
            return false;
    }

    return true; //Must be identical
}

但是,当我尝试使用下面的代码行对其进行测试时,isMatch3 返回 true。

DNAStrand str2("AACC");
bool isMatch3 = (str2 == DNAStrand("AAGC"));

我很确定 for 循环存在问题,它应该遍历 C 字符串中的每个字符,但我无法弄清楚问题是什么。在我看来,要么是那个,要么是我原来的构造函数错了。

【问题讨论】:

  • 字符串请使用std::string而不是char*/char[]/new,这样就不会有问题了。
  • 您是否忘记为起始字符串中的实际内容设置基数?目前看起来无论你传递给构造函数什么,基数都是 {'A','C','G','T',0}
  • @walnut 为清楚起见,我们不允许使用 std::string 进行此分配以“了解制作类似字符串的对象所涉及的内容并进行 [我们的] 自己的内存管理”
  • @DanBoing 好的,那就没办法了。请注意,您不会在实践中编写这样的代码。
  • 投票结束是错字,因为 bases 显然总是用相同的值初始化,这似乎不是故意的。

标签: c++ operator-overloading


【解决方案1】:

当您创建DNAStrand 对象时,您不会将startingString 存储在任何地方(您只保留其长度)。更重要的是,您为所有对象设置了相同的基本“ACGT”:

DNAStrand::DNAStrand(const char* startingString) {
    length = strlen(startingString);
    bases = new char[length + 1] {'A','C','G','T',0};
}

当您在循环中比较 bases 时,您是在比较左右对象中的“ACGT”,并且始终返回 true

解决它存储startstring:

DNAStrand::DNAStrand(const char* startingString) {
    length = strlen(startingString);
    bases = new char[length + 1] {startingString};
}

【讨论】:

  • 您的代码不是有效的 C++。无法从 const char* 初始化 char 数组。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多