lundi 22 février 2021

(C++) Does C++ has hoisting of class?

I've herad that it's illegal to implement member function in different scope such as...

class Foo{
   public:
      Foo();
}

int main(){
   Foo :: Foo(){   // implementation must be held in same scope where class is: global scope
      std::cout << "Hello" << std::endl;
   }
}

So I thought defineing a class inside main function would make it possible to implement method inside main.

#include <iostream>

int main() {

class Person {
  public:
    std::string name;
    int age;
    Person(std::string name, int age);
};

Person ::Person(std::string name, int age)
    : name(name), age(age) {
    std::cout << "Person class created as" << name << " " << age << std::endl;
}

    Person yun("yun", 18);

    std::cout << yun.name;

    Person *john = new Person("John", 15);
}

But code above spit out error as : qualified-id in declaration before '(' token
which is same error i've seen when implement method in different scope.

Is it something to do with hoisting that I've seen at JavaScript? so that class definition goes outside of main?

Aucun commentaire:

Enregistrer un commentaire