0

In python we may use self keyword to declare class variables within a member function of the class which can be subsequently used by other member functions of the class. How to do such a thing in C++.

Python Code:

class abc():
{ 
  def __init__(self):
    self.help='Mike' #self.help is the class variable and can be used in other methods
  def helpf():
    morehelp=self.help+' Bike'
}

C++ code:

 class abc
 {
   public: 
     abc();
   public: 
     void helpf(void);
 };
 abc::abc()
 {
   string help="Mike";       
 }
 void abc::helpf()
 {
   string morehelp=this->helpf+" Bike";// this keyword sounded like the one but...
 }
4

4 回答 4

3

在 C++ 中没有办法做这样的事情。您应该在类中声明成员,而不是在函数中。

于 2013-06-04T10:33:17.323 回答
1

您不能在 C++ 中的函数内声明类成员。您必须在函数之外声明它们,例如在 JAVA 中

class abc
{
public: 
   int publicInt; // This is a public class variable, and can be accesed from outside the class
   int abc();
private: 
   float privateFloat; // This is private class variable, and can be accesed only from inside the class and from friend functions
   void helpf(void);
};
于 2013-06-04T10:33:16.030 回答
0

这是不可能的。在成员函数内声明变量是该成员函数的本地变量。如果要在成员函数中使用变量,则必须声明类变量。

于 2013-06-04T10:33:32.433 回答
0

这在 Python 中是有效的,因为 Python 允许您从任何地方向对象添加属性,只需分配给它即可。它附加到该对象,而不是对象的类。为了符合 Python 的动态语言哲学,特别是它缺少变量声明,所有这些——包括关于哪些属性存在或不存在的决定——都发生在运行时

C++ 明确没有一个特定对象具有属性的概念 -所有成员变量都与类相关联,即使它们在每个实例上都采用独立值。所有可能的成员变量的集合,以及它们所持有的类型,在类范围内共享并在编译时固定下来。因此,您所要求的在 C++ 中基本上没有意义。

于 2013-06-04T11:21:05.370 回答