【发布时间】: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