5

我已经尝试了很多方法来做到这一点,我得到了一个静态的 void,并且在我制作的 Console 类上,Void 它自己工作正常:

Console::WriteLine(const char* msg)

另一方面,我得到了另一个 const char* non static void,它从中调用 Console::WriteLine void,我已经在 C# 上工作了大约一年,在 C# 上我可以轻松地做这样的事情:

string a = "Start ";
string b = a + "End";

当我在 C++ 上调用它时,它给了我一堆错误:

Player::Kill(const char* Message)
{
    Console::WriteLine("> " + Message + " <");
}

我也尝试过 strcat 的东西,但它告诉我使用 strcat_s 这并没有真正起作用,而且我尝试过使用字符串而不是 const char*,并尝试过 char*,但他们都给了我正在尝试做的事情的错误。

4

6 回答 6

8

“const”的意思是“不能改变(*1)”。因此,您不能简单地将一个 const char 字符串“添加”到另一个 (*2)。您可以做的是将它们复制到非常量字符缓冲区中。

const char* a = ...;
const char* b = ...;

char buffer[256]; // <- danger, only storage for 256 characters.
strncpy(buffer, a, sizeof(buffer));
strncat(buffer, b, sizeof(buffer));

// now buffer has the two strings joined together.

由于类似原因,您尝试使用 std::string 失败。你说:

std::string a = "Start";
std::string b = a + " End";

这转化为

b = (std::string)a + (const char*)" End";

应该没问题,只是它创建了一个额外的字符串,你可能想要的是

std::string a = "Start";
a += " End";

如果您在执行此操作时遇到编译错误,请发布它们(确保您 #include )。

或者您可以执行以下操作:

std::string addTwoStrings(const std::string& a, const std::string& b)
{
    return a + b; // works because they are both strings.
}

以下所有工作:(参见现场演示http://ideone.com/Ytohgs

#include <iostream>
#include <string>

std::string addTwoStrings(const std::string& a, const std::string& b)
{
    return a + b; // works because they are both strings.
}

void foo(const char* a, const char* b)
{
    std::string str = a;
    std::cout << "1st str = [" << str << "]" << std::endl;
    str += " ";
    std::cout << "2nd str = [" << str << "]" << std::endl;
    str += b;
    std::cout << "3rd str = [" << str << "]" << std::endl;
    str = addTwoStrings(a, " ");
    std::cout << "4th str = [" << str << "]" << std::endl;
    str = addTwoStrings(str, b);
    std::cout << "5th str = [" << str << "]" << std::endl;
}

int main()
{
    foo("hello", "world");
}

*1 或更准确地说,“不能就地改变”——你可以在表达式等中使用它,例如,例如

const size_t len = strlen("hello");
size_t newLen = len + strlen("world");
// but this would not be legal:
len += 2; // error: len is const.

2 "const char a + const char* b" 实际上是尝试添加两个指针而不是两个字符串,结果将是字符串 a 的地址加上字符串 b 的地址,其总和将是某个随机内存位置

于 2013-09-02T20:35:58.580 回答
3

char *是指针("> "和 也是" <"),您不能将指针相加。

但是,您可以使用 + 运算符连接 C++ 字符串:

Player::Kill(const std::string& Message)
{
    Console::WriteLine(("> " + Message + " <").c_str());
}
于 2013-09-02T20:24:25.533 回答
2

与其连接字符串并创建一个额外的临时对象,为什么不单独输出 3 个字符串呢?

Player::Kill(const char* Message)
{
  Console::Write("> ");
  Console::Write(Message);
  Console::WriteLine(" <");
}
于 2013-09-02T20:26:36.950 回答
1

既然你说它是 C++ 代码,就这样:

void Player::Kill(std::string const& Message)
{
    Console::WriteLine(("> " + Message + " <").c_str());
}

理想情况下,您Console::WriteLine()也被宣布参加舞会std::string const&,在这种情况下,您不需要参加.c_str()舞会。

于 2013-09-02T20:25:56.747 回答
-1
#include <iostream>
using namespace std;

string string1 = "John";
string string2 = "Smith";

float string1Len = string1.length();
float combinedLen = string1.length() + string2.length();
char combine[string2.length() + string1.length()];

for(int i = 0; i < string1Len; ++i){
    combine[i] = string1[i];
}
for(int i = string1Len; i < combinedLen; ++i){
    combine[i] = string2[i - string1Len];
}

const char * combined = combine;
于 2021-04-09T13:32:49.927 回答
-1

好吧,可以使用 const char* 进行更改,即使它是 const 我们也无法更改其值但可以更改其地址,请查看下面的类以供参考

    class String
{
private:
    const char* m_Name;
    int m_Size;
public:
    String() :m_Name(" "), m_Size(0) { m_Size = 0; }
    String(const char* name , int size) :m_Name(name),m_Size(size) {}
    String(const char* name) :m_Name(name) {}

    void Display()
    {
        LOG(m_Name);
    }
    int GetSize()
    {
        while (m_Name[m_Size] != '\0')
        {
            m_Size++;
        }
        return m_Size;
    }
    void Append(const char* nameToAppend)
    {
        //Create an empty char array pointer "*tempPtr" of size = existing const 
        //char name pointer "m_Name"  + const char pointer appending name 
        //"*nameExtention" 
        
        //this array can store both the names 
        int totalSize = 0;
        int nameToAppendSize = 0, existingNameSize = 0;
        while (nameToAppend[nameToAppendSize] != '\0')
        {nameToAppendSize++;}
        existingNameSize = this->GetSize();
        totalSize = nameToAppendSize + existingNameSize;
        char* tempPtr = new char[totalSize+1];

        //Add  existing const char name pointer "*m_Name"  +  const char pointer 
        //appending name "*nameExtention" to tempPtr,  using a loop 
        
        int currentSize = 0;
        for (int i = 0; i < existingNameSize; i++)
        {   
            tempPtr[currentSize] = m_Name[i];
            currentSize++;
        }
        for (int i = 0; i <= nameToAppendSize; i++)
        {
            if (i == nameToAppendSize)
            {
                tempPtr[currentSize] = '\0'; // this line tells compiler to stop 
                                             //  writting inside tempPtr 
            }
            else
            {
                tempPtr[currentSize] = nameToAppend[i];
                currentSize++;
            }
        }
        //--------------------------------
        //Now change the address of your const char* with tempPtr
        //This will change the contents of the const char* 
        //--------------------------------
        m_Name = (char*)tempPtr;
    }
};

        
于 2021-08-07T07:47:29.293 回答