c++ - 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?
解决方案
推荐阅读
- java - Windows系统的Java内存映射文件
- java - 如何设置列的Jtable名称
- sql - OracleSQL 比较基于整数列的日期
- javascript - 如何从 django 应用程序的视图中检索帖子数据
- c# - 无法连接到远程服务器 c# - godaddy
- python - 遍历两个列表
- sql - SQL LAG 函数和分组/排序
- ruby-on-rails - 在 rails 6 表单和允许的参数中使用 JSONB
- swift - 获取 UIView 在 UIImageView 中的位置
- javascript - 导入公钥“SubtleCrypto”时出错:提供的值无法转换为序列