在clss中使用变量(C ++) [英] Using variables in clss (C++)

查看:99
本文介绍了在clss中使用变量(C ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <iostream>
#include<string>
using namespace std;
class jani{
private:
    string Name;
public:
    void setName(string x){Name=x}
    void string getName(){return Name}


};

int main(){
   jani j1;
   j1.setName("I kill you");
   cout<<j1.getName();

return 0;
}





我的尝试:



我正在尝试在课堂上使用字符串而且有问题。



得到erroe在这一行:



void string getName(){return Name}



What I have tried:

I'm trying to use string in a class and have problem.

got erroe In this line:

void string getName(){return Name}

推荐答案

在C ++中,这些被称为对象的字段而不是变量,如普通功能的情况。



正如理查德在对你的问题的评论中提到的,问题在于你的功能本身。您对 getter and setters 的属性感到困惑[ ^ ];它有一个返回类型,需要一个参数。



setter需要一个参数,通常有 void return,这意味着它不会返回任何内容。您还可以返回指示状态的布尔值。而另一方面,getter具有返回类型( void 除外)并且不一定需要参数。您还需要了解一下返回类型;没有无效字符串返回类型。



将您的代码更改为以下内容,

In C++, these are called fields of the object not the variables, as in the case of ordinary function ones.

As Richard has mentioned in his comment to your question, the problem is with your function itself. You are confused with the properties of getters and setters[^]; which has a return type and which requires a parameter.

The setter requires a parameter and usually has a void return, which means it doesn't return anything. You can also return a boolean value indicating the status. Whereas on the other hand, a getter has a return type (other than void) and doesn't necessarily requires a parameter. You also need to learn a bit about the return types; there is no void string return type.

Change your code to the following,
void setName(string x) { Name = x; }
string getName() { return Name; }



您在语句结束时也丢失了分号,C ++需要分号才能终止语句。


You were also missing the semicolons at the end of statements, C++ requires a semicolon to terminate the statements.


void string getName(){return Name}



返回 void string 类型的函数是不可能的,因为两个关键字都是矛盾的,这可以追溯到C语言。

这是一篇关于C的好讲座,它不是浪费时间,因为C是C ++的祖先,因此大多数适用于c的内容也适用于C ++。

C编程语言 - 维基百科,免费的百科全书 [ ^ ]

https: //hassanolity.files.wordpress.com/2013/11/the_c_program ming_language_2.pdf [ ^ ]

http://www.ime。 usp.br/~pf/Kernighan-Ritchie/C-Programming-Ebook.pdf [ ^ ]


A function returning void string type is impossible because both keywords are contradictory, this go back to C language.
Here is a good lecture about C, it is not a waste of time since C is the ancestor of C++, so mostly what apply to c also apply to C++.
The C Programming Language - Wikipedia, the free encyclopedia[^]
https://hassanolity.files.wordpress.com/2013/11/the_c_programming_language_2.pdf[^]
http://www.ime.usp.br/~pf/Kernighan-Ritchie/C-Programming-Ebook.pdf[^]


这篇关于在clss中使用变量(C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆