首页 > 解决方案 > 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

标签: c++

解决方案


TestClass test;是声明类型变量的语法TestClass。变量是该类型的一个实例。在这种情况下,它是 的一个实例TestClass

为什么可以调用非静态类方法...

因为您已经创建了一个实例。

...没有首先创建类的实例?

你的前提是错误的。


推荐阅读