使用C ++帮助指针和字符; [英] Help Pointers and chars in C++;
问题描述
嘿.当我这样做时:
char * suit ="Hearts"; cout<< *西装;它印有Hearts;
但是在这种情况下:仅打印"m".为什么?
Hey.When I do this:
char *suit = "Hearts"; cout<<*suit; it prints Hearts;
But in this case: It is only printing "m". WHY?
#include "stdafx.h"
#include <iostream>
using namespace std;
class yup{
public:
yup(char *);
void print();
private:
char *name;
};
yup::yup(char *x)
{
name = x;
}
void yup::print()
{
cout<<*name;
cout<<endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
yup t("missak");
t.print();
return 0;
}
推荐答案
在这里,您仅将x的地址分配给名称.并且x的地址是"missak"的"m".
Here you are only assigning the adress of x into name. And at the adress of x is the ''m'' of "missak".
yup::yup(char *x)
{
name = x;
}
在此打印地址名称"的内容.内容是一个字符.是字母"m".
Here the content of the adress "name" is printed. And the content is a single char. It''s the letter ''m''.
void yup::print()
{
cout<<*name;
cout<<endl;
}
您必须将整个字符串复制到您的私有成员中.
在C中,您可以这样操作,例如
You have to copy the whole string into your private member.
In C you could do this like this e.g.
char szName[BUFF_SIZE];
void yup(const char *x)
{
if( strlen(x) < BUFF_SIZE )
{
strcpy(szName, x);
}
}
在C ++中,还有一个用于字符串的类.我目前在这里没有很好的参考.但是,在Google Project上进行一些Google搜索或搜索将对您有所帮助.
In C++ there is also a class for strings. I don''t have a good reference right here at the moment. But a little google or search on CodeProject will help you..
cout<< * name;
cout<<*name;
您应该改写
You should write instead
cout << name;
顺便说一句,您不应该存储指向原始字符数组的指针(它可能是临时的).您应该改为复制数组内容.更好的是,您可以使用std::string
:
By the way you shouldn''t store a pointer to the original character array (it could be a temporary). You should instead copy the array content. Even better you could use a std::string
:
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
class yup{
public:
yup(char *x ):name(x){};
void print();
private:
string name;
};
void yup::print()
{
cout << name;
cout << endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
yup t("missak");
t.print();
return 0;
}
当我这样做时:
char *suit = "Hearts"; cout<<*suit;
它印有《心》;
它不应该,它应该只打印字符"H".您要做的是,取消引用指向char的指针,因此它只是一个char.这就是为什么它只是从您的班级打印出来的字符.
如果希望类打印整个字符串,请不要取消引用char指针.
it prints Hearts;
It shouldn''t, it should print the character ''H'' only. What you do is, you dereference the pointer-to-char, so it is only a char. That''s why it''s only the char that is printed from your class.
If you wish the class to print the whole string, don''t dereference the char pointer.
这篇关于使用C ++帮助指针和字符;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!