C#学习 - 方法的定义、调用、调试

方法

  • 方法(Method)是由C/C++中的函数(Function)发展而来的
//C语言
#include <stdio.h>
int Add(int x, int y)
{
   
	return x + y;
}//函数
int main(void)
{
   
	int a = 4;
	int b = 2;
	int c = Add(a, b);
	printf("%d + %d = %d\n", a, b, c);
	return 0;
}
//C++
#include <iostream>
int Add(int x, int y)
{
   
	return x + y;
}//函数
int main()
{
   
	int a = 4;
	int b = 2;
	int c = Add(a, b);
	std::cout << a << " + " << b << " = " << c;
	return 0;
}

方法是面向对象,当一个函数以类的成员出现的时候就叫方法,所以方法又叫成员函数
在编写C++程序时,选择添加类(Class),然后输入类名,后面的 .h 文件就是类的声明,而 .cpp 文件就是类的定义(在C#中类的声明和定义是放在一起的)C++程序添加类

//ABC.h - 类的声明
#pragma once
class ABC
{
   
public:
	void ShowHello();
};

//ABC.cpp - 类的定义
#include "ABC.h"
#include <iostream>
void ABC::ShowHello()
{
   
	std::cout << "Hello World";
}

//use.cpp
#include <iostream>
#include "ABC.h"
int main()
{
   
	ABC* pABC = new ABC();
	//此处已经有了C#方法的雏形了
	pABC->ShowHello();
	return 0;
}
  • 方法是类(或结构体)的成员

C#中函数不能独立于类(或结构体)之外
只有作为类(或结构体)的成员出现时,函数才能被称为方法

namespace ConsoleApp1
{
   
    int Add(int x, int y)
    {
   
        return x + y;
    
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值