【发布时间】:2015-12-25 14:25:39
【问题描述】:
我正在尝试使用以下签名实现一个函数:char* findx (const char* s, const char* x),其中两个参数是 C 风格的字符串,返回值是指向 s 中第一次出现的 x 的指针。
这是我的实现:
char* findx (const char* s, const char* x) {
// check if s and x valid pointers
assert(s);
assert(x);
// get lengths of s and x
size_t len_s = m_strlen(s);
size_t len_x = m_strlen(x);
// check if x substring (or equal to) of s
assert(len_s >= len_x);
char* p_to_match = nullptr;
// traverse s
for (size_t i = 0; i < len_s; ++i) {
if (*(s + i) == *x) {
p_to_match = const_cast<char*>(s + i);
//-----------^ can't assing const char* to char* ???
if (len_x == 1) return p_to_match;
// the current s's matched the x's zeroth, so next test is for the next elements
const char* next_s = (s + i + 1);
const char* first_x = (x + 1);
for (size_t j = 0; j < len_x - 1; ++x) {
// if any of the rest of x's elements don't match, break the inner for loop
if (*(next_s + j) != *(first_x + j)) break;
// if all the rest of x's elements match return ref_to_match
if (j == len_x - 2) return p_to_match;
}
}
}
return nullptr;
}
我遇到的问题是我不喜欢显式类型转换 (const_cast<char*>) 并且我想用其他东西替换它,但是目前我无法看到如何在不更改返回值的情况下执行此操作 (到const char*)或论点(到char* s),所以我的问题是:
有没有办法实现函数,特别是返回变量,不用const_cast<char*>,不改变函数签名?
【问题讨论】:
-
IMO,调用者应该是做演员的人。
-
旁注:您将
const char*作为参数并返回char*。因此,从概念上讲,您允许更改char*的基础值。但如果它是const char*的一部分,那么您也允许自己更改const char*。这在概念上是错误的。如果您想让它们保持相关,您应该将它们全部设为 const 或全部设为 non-const。