我是一名真正的c ++初学者,我在c ++练习中的char数组输出有问题。我被要求将某个UML类转换为c ++,并使用main中给定的参数生成有效的输出。这里的代码:
#include <iostream>
#include <stdlib.h>
/*My class defintion book*/
class Book
{ protected:
long int number;
char author[25];
int year;
bool lent;
void setLent(bool x);
bool getLent();
public:
Book(long int n, char a[25], int j, bool x);
long int getNr();
int getYear();
void print();
};
/*Method definition Book*/
Book::Book(long int n, char a[25], int j, bool x)
{number=n;
author=a;
year=j;
lent=x;}
long int Book::getNr()
{return number; }
int Book::getYear()
{return year;}
void Book::setLent(bool x)
{lent=x;}
bool Book::getLent()
{return lent;}
void Book::print()
{
std::cout << "Book Nr: " << number << std::endl;
std::cout << "Author: " << author << std::endl;
std::cout << "Year: " << year << std::endl;
if (lent==0)
std::cout << "Lent [yes/no]: no" << std::endl;
else
std::cout << "Lent [yes/no]: yes" << std::endl;
}
/*MAIN*/
int main()
{
Book b1(123456, "test", 2014, false);
b1.print();
system("pause");
return 0;
这是我的输出:
Book Nr: 123456
Author: b<Vv-[[vóYA
Year: 2014
Lent [yes/no]: no
Press any key to continue...
如您所见,除“作者”之外,所有输出均有效。那里我胡扯。请注意,我必须使用char作为类型。因为它是在UML类中给出的,所以我不得不转换为c ++。
我真的到处搜寻。但是没有找到正确的解决方案。我觉得这将是一个非常简单的...
在此先感谢您的帮助!
这样做不起作用的原因是,您将指针 分配author
给另一个指针 a
,该指针随后超出了范围...因此您只能author
指向一些垃圾。如果要坚持使用字符数组,则必须复制所有a
指向的数据:
strcpy(author, a);
但是,由于它是C ++,因此您应该只使用字符串,这些字符串更易于处理:
class Book {
...
std::string author;
....
};
Book::Book(long int n, const std::string& a, int j, bool x)
: author(a), ...
{ }
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句