【问题标题】:How to work with char* inside a class如何在课堂上使用 char*
【发布时间】:2012-05-26 02:08:14
【问题描述】:

我是 C++ 新手,并且正在通过教科书进行一些自我培训。我需要创建一个新类“String”。它必须使用构造函数将字符串初始化为由指定长度的重复字符组成。

我不知道如何将任何内容分配给 char* 变量。根据分配,我不能使用标准字符串库来执行此操作。我需要在构造函数中做什么?

#include "stdafx.h"
#include <cstdlib>
#include <iostream>
#include <string.h>

using namespace std;

class String {
  protected:
    int  _len;

  public:
      char *buff;
    String (int n, char* c);
};

int main()
{
  String myString(10,'Z');
  cout << myString.buff << endl;

  system("PAUSE");
  return 0;
}

String::String(int n, char* c)
{
  buff = new char[n];

}

【问题讨论】:

  • 你可以使用像strlen这样的C字符串函数吗?
  • 希望下一章能告诉你你需要一个析构函数、一个拷贝构造函数和一个拷贝赋值运算符。然后之后的章节将教你永远不要使用裸指针。后面的章节会教你使用std::string

标签: c++ class constructor char


【解决方案1】:

你快到了:因为你需要重复的字符,你不应该传递char*,而只是简单的char。 C 字符串的缓冲区也需要比字符串长一个字符;缓冲区的最后一个元素必须是零字符\0

String::String(int n, char c) {
    buff = new char[n+1];
    for (int i = 0 ; i != n ; buf[i++] = c)
        ;
    buf[n] = '\0';
}

请注意,将 buf 设为公共成员变量不是一个好主意:String 的用户不应重新分配新缓冲区,因此提供访问器 char* c_str() 并将 buf 设为私有可能是好主意。

【讨论】:

  • 在同样的思路上,c_str 函数最好返回 char const*
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-30
  • 1970-01-01
  • 1970-01-01
  • 2019-07-03
  • 2019-05-13
  • 2015-03-31
  • 2015-06-29
相关资源
最近更新 更多