我正在尝试使用以下签名实现一个函数:char* findx (const char* s, const char* x)
,其中两个参数是 C 风格的字符串,返回值是指向第一次出现的 x
的指针。在s
.
这是我的实现:
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*>
的情况下实现函数,特别是返回变量? , 不改变函数签名?
最佳答案
您应该使p_to_match
和函数的结果类型const char*
。您不能返回 char*
以指向您作为 const char*
没有 const_cast
如果可能,您将能够允许将(非 const char* 返回类型)写入您的参数,即 const
(例如通过传递 findx(s, s)) .这意味着 const
根本没有意义
当 s
为 char*
时,您可能还想返回 char*
,当 s
是 const char*
。您可以为该模板使用两个单独的函数。
关于c++ - 在函数 findx() 中是否有替代 const_cast<char*> 的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34463664/