简体   繁体   English

C++ 从'const char*' 到 char* 的无效转换

[英]C++ invalid conversion from 'const char*' to char*

I am new to C++.我是 C++ 的新手。 I have an exercise about constructor with const char* parameter.我有一个关于带有 const char* 参数的构造函数的练习。

class Book
{
private: 
   char* title;
}
public:
   Book (const char* title)
   {
      this->title = title;
   } 

When I code the constructor like that, I receive error cannot convert const char to char*.当我这样编写构造函数时,我收到错误无法将 const char 转换为 char*。 I tried using strcpy(this->title, title);我尝试使用strcpy(this->title, title); then, it run, but I don't get the expected result.然后,它运行,但我没有得到预期的结果。 Can anyone help me.谁能帮我。 Thank you very much.非常感谢。

C++ doesn't let you easily change a const char * into a char * since the latter has no restrictions on how you can change the data behind that pointer. C++ 不允许您轻松地将const char *更改为char *因为后者对如何更改该指针后面的数据没有限制。

If you're doing C++, you should be avoiding char * (legacy C) strings as much as possible.如果您正在使用 C++,则应尽可能避免使用char * (传统 C)字符串。 By all means take them as parameters if you must, but you should be turning them into C++ strings at the earliest opportunity:如果必须,请务必将它们作为参数,但您应该尽早将它们转换为 C++ 字符串:

class Book {
private: 
   std::string m_title;
public:
    Book (const char *title) {
        m_title = title;
    }
};

The one thing you don't want to become is a C+ developer, that strange breed that never quite made the leap from C across to the C++ way of thinking :-)不想成为的一件事是 C+ 开发人员,这个奇怪的品种从来没有从 C 跨越到 C++ 的思维方式:-)


And, actually, if a given book is never expected to change its title, you're better off making it constant and initialising it, rather than assigning to it, something like:而且,实际上,如果永远不会期望给定的书改变其标题,那么最好将其设置为常量并对其进行初始化,而不是分配给它,例如:

#include <iostream>
#include <string>

class Book {
    public:
    Book (const char* title): m_title(title) {};
    void Dump() { std::cout << m_title << "\n"; }

    private:
    const std::string m_title;
};

int main() {
    Book xyzzy("plugh");
    xyzzy.Dump();
}

You are doing an exercise, did the course you are following not explain what you are supposed to do?您正在做一个练习,您所遵循的课程是否没有解释您应该做什么?

I would guess that this is an exercise in dynamic memory allocation and what you are expected to do is use strcpy after you have allocated some memory so that you have somewhere to copy the string to.我猜这是动态内存分配的练习,您应该在分配一些内存后使用strcpy以便将字符串复制到某个地方。 Like this像这样

this->title = new char[strlen(title) + 1];
strcpy(this->title, title);

You need to allocate one extra char because C style strings are terminated with an additional nul byte.您需要分配一个额外的字符,因为 C 样式字符串以额外的空字节终止。

But any C++ programmer who was doing this for real (instead of it being a learning exercise) would use a std::string as paxdiablo says.但是任何真正做到这一点的 C++ 程序员(而不是学习练习)都会像 paxdiablo 所说的那样使用std::string

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM