2009-06-28 71 views
2

我在写一个简单的程序。它只有一个类。有一个私人成员'char * number'和两个函数(会有更多,但首先这些应该正常工作:))。在C++中打印char *

第一个应该复制的“源”到“数字”变量(和我想的地方现在的问题):

LongNumber::LongNumber(const char * source){ 
     int digits = strlen(source); 

     char* number = new char[digits+1]; 
     strcpy(number, source); 
     // cout<<number<<endl; - if the line is uncommented, 
     // the output is correct and there isn't a problem 

} 

和打印功能:

void LongNumber::print(){ 
    cout<<number<<endl; 
    // when I try to print with the same line of code here..it crashes 
} 

当然,我错过了一些东西......但是什么?

(由于这是我的第一篇......你认为标签corrected..how将您所标记的职位?)

预先感谢您:)

回答

5

LongNumber构造你声明一个名为number一个新的局部变量,并用新char数组初始化:

char* number = new char[digits+1]; 

相反,你应该离开了char*,所以它看起来并不像一个新的变量声明并使用对象的成员变量:

number = new char[digits+1]; 

在当前的代码,所述成员变量number永远不会被初始化,并在以后使用它在print导致一个错误。

6

您的编号char *数组在退出构造函数时会超出范围。当到达print()时,由于程序不再访问* number最初指向的内存,它将崩溃(即分段错误)。为了解决这个问题,而是执行此操作:

class LongNumber 
{ 
    char *number; 
    LongNumber(const char *source); 
    ~LongNumber(); 
    void print(); 
}; 

LongNumber::LongNumber(const char * source){ 
     int digits = strlen(source); 

     number = new char[digits+1]; 
     strcpy(number, source);  
} 

void LongNumber::print(){ 
    cout<<number<<endl; 
} 

不要忘记做到以下几点:

LongNumber::~LongNumber() 
{ 
    delete [] number; // to avoid memory leaks 
} 

我也强烈建议使用STL ::字符串,而不是使用char *您*号变量,因为您不必自己处理内存管理开销,并且复制字符串也会更容易。

1

你的问题是在构造函数:

LongNumber::LongNumber(const char * source) 
{ 
    ... 
    // you are declaring a new local variable called `number` here 
    char* number = new char[digits+1]; 
    strcpy(number, source); 
    ... 
} 

你没有复制到被称为number类的成员变量,您声明在构造函数体新的本地变量和使用。类成员变量未使用,可能未定义。对于一个指针成员,这意味着该值可以是任何无效值 - 那么当你调用打印:

void LongNumber::print() 
{ 
    cout<<number<<endl; 
    // when I try to print with the same line of code here..it crashes 
} 

number您使用这里,是类成员变量,正如我们所说的是不确定的。因为它试图使用该无效指针,所以调用cout将会崩溃。

解决方法是使构造函数中使用正确的类成员变量:

LongNumber::LongNumber(const char * source) 
{ 
    ... 
    // use the class member variable `number` here 
    number = new char[digits+1]; 
    strcpy(number, source); 
    ... 
} 
1

它看起来对我来说,你的声明号码作为一个局部变量。如果你希望能够到另一个函数中再次调用它,你必须声明它的类定义......像这样:

class LongNumber{ 
public: 
     int digits; 
     char* number; 
     LongNumber(const char * source); 
     void print(); 
} 

LongNumber::LongNumber(const char * source){ 
     digits = strlen(source); 
     number = new char[digits+1]; 
     strcpy(number, source); 
     // cout<<number<<endl; - if the line is uncommented, 
     // the output is correct and there isn't a problem 
} 

void LongNumber::print(){ 
    cout<<number<<endl; 
    // when I try to print with the same line of code here..it crashes 
} 

希望帮助!

+0

哎呀,似乎有一百万人回答了这个问题,而我......对不起,关于这个:) – micmoo 2009-06-28 07:30:45