c++ - C++: Why is a non-static class method able to be called without a class instance?
问题描述
It's been a while since I have written any C++, so when looking up some basic examples to get me started, I was surprised to see something like this:
#include <iostream>
class TestClass {
public:
void testMethod(){
std::cout << "Hello!";
}
};
int main()
{
TestClass test; // Not being instantiated
test.testMethod(); // Method still able to be called successfully!
}
How is it possible that a non-static method of a class can be called without an instance of the class being created first?
Working example: http://cpp.sh/3wdhg
解决方案
TestClass test;
是声明类型变量的语法TestClass
。变量是该类型的一个实例。在这种情况下,它是 的一个实例TestClass
。
为什么可以调用非静态类方法...
因为您已经创建了一个实例。
...没有首先创建类的实例?
你的前提是错误的。
推荐阅读
- swift - 在轮播列表中获取偏移值
- spring - 嵌套 @ConfigurationProperties 的 Spring Boot 启动期间没有错误消息
- python - 如何将同一行中的列作为熊猫中的 .loc 进行子集化
- r - 使用脆弱项测试 cox 比例风险假设时出错
- java - 我的世界插件开发中的错误:它是最新的吗?IllegalStateException:初始初始化
- zip - 损坏的 zip 文件(尝试了几乎所有工具都无法修复)
- javascript - Odin 项目 - 基础 4 练习 - sumAll
- android - Android只更新TextView的部分文字
- c# - NET Core 3.1 MVC 输入验证不起作用
- aws-lambda - DynamoDB // Lambda // 不一致的记录