C++怎么调用类中的函数
1. 栈上对象 调用普通成员方法
普通成员方法需要通过类的对象实例(或指针、引用)来调用。
示例:
class MyClass {
public:
void normalMethod() {
std::cout << "普通成员方法被调用" << std::endl;
}
};
int main() {
MyClass obj; // 创建对象实例
obj.normalMethod(); // 通过对象调用
MyClass* ptr = &obj; // 对象指针
ptr->normalMethod(); // 通过指针调用
MyClass& ref = obj; // 对象引用
ref.normalMethod(); // 通过引用调用
}
2. 调用静态成员方法
静态成员方法(static
方法)属于类本身,无需对象实例,可直接通过类名调用。
示例:
class MyClass {
public:
static void staticMethod() {
std::cout << "静态方法被调用" << std::endl;
}
};
int main() {
MyClass::staticMethod(); // 直接通过类名调用
MyClass obj;
obj.staticMethod(); // 也可通过对象调用(不推荐,易混淆)
}
3. 堆上对象 调用普通成员方法
示例:
class MyClass {
public:
void method() {
std::cout << "通过指针/引用调用" << std::endl;
}
};
int main() {
MyClass* ptr = new MyClass(); // 动态分配对象
ptr->method();
delete ptr; // 释放内存
MyClass obj;
MyClass& ref = obj;
ref.method();
}
4. 在类内部调用其他方法
类的方法可以直接调用本类的其他成员方法(包括私有方法)。
示例:
class MyClass {
private:
void privateMethod() {
std::cout << "私有方法被调用" << std::endl;
}
public:
void publicMethod() {
privateMethod(); // 直接调用私有方法
}
};
int main() {
MyClass obj;
obj.publicMethod(); // 输出 "私有方法被调用"
}
5. 调用常量方法(const
方法)
如果对象是常量(const
),只能调用标记为 const
的成员方法。
非常量,只能使用非const 方法
示例:
#include<iostream>
using namespace std;
class MyClass {
public:
void nonConstMethod() {
std::cout << "非 const 方法" << std::endl;
}
void constMethod() const {
std::cout << "const 方法" << std::endl;
}
};
int main() {
const MyClass constObj;
MyClass noconstObj;
// constObj.nonConstMethod(); // 错误:不能调用非 const 方法
constObj.constMethod(); // 正确:调用 const 方法
noconstObj.nonConstMethod(); // 正确:调用 非 const 方法
//noconstObj.ConstMethod(); // 错误:调用 const 方法
}
6. 在继承中调用父类方法
子类可以直接调用父类的公有或保护方法。如果方法被重写(override),可通过作用域运算符 ::
显式调用父类版本。
示例:
class Parent {
public:
void method() {
std::cout << "父类方法" << std::endl;
}
};
class Child : public Parent {
public:
void method() {
std::cout << "子类方法" << std::endl;
Parent::method(); // 显式调用父类方法
}
};
int main() {
Child obj;
obj.method(); // 先输出 "子类方法",再输出 "父类方法"
}