代码之家  ›  专栏  ›  技术社区  ›  P N Singh

在CPP Oops中调用对象而不创建它

  •  -1
  • P N Singh  · 技术社区  · 12 月前

    不幸的是,在下面的代码中,我没有创建/命名任何对象,编译时也没有出现任何错误,并且能够访问成员函数。我需要这种行为的方式是在堆栈中创建一个临时对象——如果是这样的话——如果我想在代码的后面访问某个地方,我可以访问它吗。

    #include <iostream>
    #include <string>
    
    class Person {
    public:
        std::string name;
        int age;
    
        Person(std::string n, int a) : name(n), age(a) {}
        void getInfo() {
            std::cout << "Name : " << name << std::endl;
            std::cout << "Age : " << age << std::endl;
        }
    };
    
    class Student : public Person {
    public:
        int rollNo;
        Student(std::string n, int a, int r) : Person(n, a), rollNo(r) {}
    
        void getInfo() {
            std::cout << "Name : " << name << std::endl;
            std::cout << "Age : " << age << std::endl;
            std::cout << "Roll No : " << rollNo << std::endl;
        }
    };
    
    int main(int argc, const char* argv[]) {
        Student("Goofupp", 27, 1001).getInfo();  // does any memory also created here ?? how to understand this behaviour
    
        Student rahul("Rahul", 23, 1002);  // there is block of memory allocated for rahul
    
        rahul.getInfo();
    
        return 0;
    }
    

    我原本以为会出现错误,说“声明没有定义任何东西”,就像我们在下面定义时得到的那样

    int main()
    {
      int;     
      cout<<"hello\n";     
      return 0; 
    }
    
    2 回复  |  直到 12 月前
        1
  •  3
  •   463035818_is_not_an_ai    12 月前

    这条线

    Student("Goofupp", 27, 1001).getInfo();
    

    调用构造函数以创建 Student 它是一个暂时的对象,在 ; 它没有名字。因为它一直活着,直到 ; 你可以调用一个方法。

    不幸的是,在下面的代码中,我没有创建任何对象[…]

    您确实创建了一个临时对象。

    不幸的是,在下面的代码中,我没有[…]命名任何对象[…]

    临时对象不需要名称。不需要名称,因为无论如何,在对象的生命周期结束后,您都无法引用该对象。

    我原本以为会出现错误,说“声明没有定义任何东西”

    没有这样的错误,因为该行不是声明。

        2
  •  0
  •   Newbie852    12 月前

    这是因为我们可以显式地调用类的构造函数。这就是为什么这条线:

    Student("Goofupp",27,1001).getInfo();
    

    工作正常。 逻辑很简单。它只是首先调用相关构造函数,在你的例子中,它是:

    Student(string n, int a, int r);
    

    由于调用了对象的构造函数,因此分配了对象的内存。然后,在该对象上,您调用了getInfo()方法。getInfo()给出一些打印输出,然后函数结束。该对象没有存储在任何地方,因此它超出了作用域,并在该行之后被析构函数销毁。

    第二个问题的答案是,这是暂时的,所以你不能在以后的代码中使用它。要使用它,您可以命名它,将其分配给另一个Student对象,或者传递给其他函数:

    class Student { 
        public:
            //Provide a constructor
            Student (string _name, int _age, int _rollNo) : name(_name), age(_age), rollNo(_rollNo) {}
    
            void getInfo() {
                /* Give your implementation */
            }
    
        private:
            string name;
            int age;
            int rollNo;
    };
    
    void doSomething(Student s) {
        //Assuming this calls getInfo method
        s.getInfo();
    }
    
    int main() {
    
        Student s1 = Student("Example1", 20, 1000); //Assign it to other Student object
        Student s2("Example2", 20, 1001); //Give it a name
        
        doSomething(Student("Example3", 20, 1002)); //Or pass it to other function
    
        return 0;
    }