c++类和C#中定义类的方法异同之处:
1. 相同处:
1.1.都需要使用 class标识;
1.2.都包含有成员:函数,属性;
1.3.都有private public protect 标识的成员
2.不同之处:
2.2. C++申明类及成员时格式:
class Member { public: void SetName(string name); string GetName(); private: string name; };
一般在class的末尾处需要一个英文分割符号“;”,public private protect 成员时,集中式生命,而这是在c#中没有出现,或者没有这么严格要求。
public class Member { private string name; public void SetName(string name) { this.name=name; } public string GetName() { return this.name; } } 或者 简单的一个get;set;就可以替代上边的函数,不过getName,setName函数是在预编译时,自动生成的。 public class Member { public string Name{get;set;} }
2.2. 以来文件的引入方式不同:
c++ 使用:
#include<iostream> using std::cout #include “test.h”
c#:
using System; using System.IO;
怎么写一个完成c++的类:
#include <iostream> using std::cout; using std::endl; #include <string> // program uses C++ standard string class. using std::string; #include <conio.h> // GradeBook class definition class GradeBook { public: // constructor initializes courseName with string supplited as argument. GradeBook(string name) { this->courseName=name; } // end GradeBook constructor // function to set the course name void setCourseName(string name) { this->courseName=name;// store the course name in the object. }// end function setCourseName // function to get the course name. string getCourseName() { return courseName;// return object's courseName }// end function getCourseName // display a welcome message to the GradeBook user void displayMessage() { // call getCourseName to get the courseName cout<<"Welcome to the grade book for \n"<<getCourseName()<<"|"<<endl; }// end function displayMessage private : string courseName; };// end class GradeBook // function main begins program execution int main() { // create two GradeBook objects. GradeBook gradeBook1("CS101 Introduction to C++ programing");; GradeBook gradeBook2("CS102 Data Structures in C++"); // display initial value of courseName for each GradeBook cout<<"gradeBook1 created for course:"<<endl; gradeBook1.displayMessage(); cout<<"gradeBook2 created for course:"<<endl; gradeBook2.displayMessage(); cout<<"Test the get function"<<endl; cout<<"gradeBook1 call getCourseName"<<gradeBook1.getCourseName()<<endl; cout<<"gradeBook2 call getCourseName"<<gradeBook2.getCourseName()<<endl; std::cin.get(); return 0; // indicates successful termination. }// end main