c++ 类方法里面调用本类的其他类方法 demo
时间: 2023-08-08 14:12:42 浏览: 132
好的,下面是一个示例代码,演示了一个类方法如何调用本类的其他方法:
```c++
class MyClass {
public:
void method1() {
// 调用本类的其他方法
method2();
method3();
}
private:
void method2() {
cout << "这是方法2" << endl;
}
void method3() {
cout << "这是方法3" << endl;
}
};
int main() {
MyClass obj;
obj.method1(); // 调用方法1
return 0;
}
```
在上面的代码中,MyClass 类有三个方法:method1、method2 和 method3。在 method1 方法中,我们可以通过直接调用 method2 和 method3 方法来实现调用本类的其他方法。注意,这里的 method2 和 method3 都是私有方法,只能在类内部进行调用。
在 main 函数中,我们创建了一个 MyClass 类的对象 obj,并调用了它的 method1 方法。当我们运行程序时,输出结果如下:
```
这是方法2
这是方法3
```
可以看到,method1 方法成功地调用了本类的其他方法 method2 和 method3。
相关问题
C# 托管类调用c++ 导出类 demo
好的,下面是一个简单的示例:
首先,在C++中定义一个导出类:
```c++
class __declspec(dllexport) MyCPPClass {
public:
MyCPPClass();
~MyCPPClass();
void DoSomething();
};
```
然后,在C#中定义一个托管类:
```c#
using System.Runtime.InteropServices;
public class MyCSharpClass {
[DllImport("MyCPPClass.dll")]
private static extern IntPtr MyCPPClass_Create();
[DllImport("MyCPPClass.dll")]
private static extern void MyCPPClass_Destroy(IntPtr instance);
[DllImport("MyCPPClass.dll")]
private static extern void MyCPPClass_DoSomething(IntPtr instance);
private IntPtr instance;
public MyCSharpClass() {
instance = MyCPPClass_Create();
}
~MyCSharpClass() {
MyCPPClass_Destroy(instance);
}
public void DoSomething() {
MyCPPClass_DoSomething(instance);
}
}
```
在托管类中,我们使用DllImport属性来声明C++导出函数的名称和库的名称。然后,我们使用IntPtr类型来存储C++对象的实例,并在构造函数和析构函数中调用Create和Destroy函数来创建和销毁C++对象。
最后,在托管类中添加一个DoSomething方法来调用C++对象的DoSomething方法。
现在,我们就可以在C#中创建MyCSharpClass对象,并调用它的DoSomething方法来调用C++对象的DoSomething方法了。
阅读全文
相关推荐










