首页 > 解决方案 > C++ 有提升类吗?

问题描述

我听说在不同的范围内实现成员函数是非法的,例如......

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;
   }
}

所以我认为在 main 函数中定义一个类可以实现 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);
}

但是上面的代码会产生一个错误:qualified-id in declaration before '(' token
这与我在不同范围内实现该方法时看到的错误相同。

这与hoisting我在 JavaScript 中看到的有关吗?所以类定义超出了main?

标签: c++classc++11

解决方案


推荐阅读